首页 > 解决方案 > 导航组件有条件的popUpTo?

问题描述

导航组件的新手。我正在努力实现这一目标,但我不知道如何:

我有3个片段:

FragmentAFragmentListFragmentAdd

如果我尝试从FragmentMaintoFragmentList但列表为空,它应该直接转到FragmentAdd(它不是真的直接,因为我正在检查 FragmentList 上的列表,但对于用户来说它应该看起来像它)。如果我打开FragmentAdd并返回(通过按返回按钮或工具栏上的返回)它应该返回FragmentMain(因为FragmentList仍然是空的)但是如果我添加一些东西它应该返回到FragmentList.

我试过了

<fragment
    android:id="@+id/fragmentMain" >
    <action android:id="@+id/action_fragmentMain_to_fragmentList
        app:destination="@id/fragmentList"
        app:popUpTo="@id/fragmentMain"
        app:popUpToInclusive="true"/>
</fragment>

问题是,如果我按回FragmentAdd它会转到FragmentList,检查列表是否仍然为空并返回FragmentAdd。如果我弹出FragmentList然后添加一些东西它会去FragmentMain而不是列表。

使用 Android 导航组件的条件后退导航的不同之处在于我可以将内容添加到FragmentListfromFragmentAdd

请问有什么建议吗?

标签: androidandroid-architecture-navigation

解决方案


app:popUpTo="@id/FragmentList" and app:popUpToInclusive="true"在 action_fragmentList_to_fragmentAdd 中使用

<fragment
    android:id="@+id/fragmentMain" >
    <action android:id="@+id/action_fragmentMain_to_fragmentList
        app:destination="@id/fragmentList"/>
</fragment>
<fragment
    android:id="@+id/fragmentList" >
    <action android:id="@+id/action_fragmentList_to_fragmentAdd
        app:destination="@id/fragmentAdd"
        app:popUpTo="@id/fragmentList"
        app:popUpToInclusive="true"/>
</fragment>
<fragment
    android:id="@+id/fragmentAdd" >
</fragment>

推荐阅读