美文网首页
Android-Navigation中返回到指定的Fragmen

Android-Navigation中返回到指定的Fragmen

作者: 100个大西瓜 | 来源:发表于2023-08-01 19:28 被阅读0次

一个情景如下
在Navigation中依次打开了A、B、C 三个Fragment


导航顺序

当打开了CFragment之后,希望返回按钮的事件是直接返回到A,而不是B
这时候可以在nav.xml中配置,主要是针对 B -> C 这个action

  <?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <fragment
        android:id="@+id/BFragment"
        android:name="com.shenby.navigation.abc.BFragment"
        android:label="BFragment"
        tools:layout="@layout/fragment_d">
        <action
            android:id="@+id/action_BFragment_to_CFragment"
            app:destination="@id/CFragment"
            app:popUpTo="@id/AFragment"
            app:popUpToInclusive="false" />
    </fragment>
    <fragment
        android:id="@+id/CFragment"
        android:name="com.shenby.navigation.abc.CFragment"
        android:label="CFragment"
        tools:layout="@layout/fragment_c" />
</navigation>

其中
popUpTo:是指定这个destination的返回目标AFragment;
app:popUpToInclusive="false" :true:清除掉AFragment并重建;fasle:利用已有的AFragment

增加了菜坑的经历,明明验证验完了,觉得都ok了,然后在navigate中增加了一个通用的动画参数,导致失效了

 /**
     *Navigation间跳转的通用动画配置
     */
    protected static final NavOptions DEFAULT_NAV_OPTIONS_ANIMATION = new Builder()
            .setEnterAnim(R.anim.slide_in_right)
            .setExitAnim(R.anim.slide_out_left)
            .setPopEnterAnim(R.anim.slide_in_left)
            .setPopExitAnim(R.anim.slide_out_right)
            .build();

    /**
     * 跳转到指定的fragment
     *
     * @param directions
     */
    protected void navigate(@NonNull NavDirections directions) {
        final NavController navController = NavHostFragment.findNavController(this);
        final NavDestination currentDestination = navController.getCurrentDestination();
        if (currentDestination == null) {
            return;
        }
        if (currentDestination.getId() != getCurrentDestinationId()) {
            return;
        }
        navController.navigate(directions,DEFAULT_NAV_OPTIONS_ANIMATION);
    }

导致了原来添加的跳转回AFragment失效
临时的解决方式是在修改nav.xml配置,直接配置动画,如下

    <fragment
        android:id="@+id/BFragment"
        android:name="com.shenby.navigation.abc.BFragment"
        android:label="BFragment"
        tools:layout="@layout/fragment_b">
        <action
            android:id="@+id/action_BFragment_to_CFragment"
            app:destination="@id/CFragment"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right"
            app:popUpTo="@id/AFragment"
            app:popUpToInclusive="false" />
    </fragment>

然后java跳转的代码直接是

protected void navigate(@NonNull NavDirections directions) {
      navController.navigate(directions);
}

ok

相关文章

网友评论

      本文标题:Android-Navigation中返回到指定的Fragmen

      本文链接:https://www.haomeiwen.com/subject/staypdtx.html