Android-Navigation中返回到指定的Fragment,Navigation弹出中间的Fragment

一个情景如下
在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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容