使用导航组件按“后退”按钮向上导航

时间:2020-02-11 20:13:37

标签: android android-architecture-navigation

我使用导航组件从一个片段导航到另一个片段。但是,当用户按下“后退”按钮时,我想导航回到第一个片段。但是它继续显示第二个片段。这是我的nav_graph:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/nav_graph"
    app:startDestination="@id/fragment1">
    <fragment
            android:id="@+id/fragment2"
            android:name="com.myapp.ui.fragments.Fragment2"
            android:label="fragment_2" />
    <fragment
            android:id="@+id/fragment1"
            android:name="com.myapp.ui.fragments.Fragment1"
            android:label="fragment_1">

        <action
                android:id="@+id/action_fragment1_to_fragment2"
                app:destination="@id/fragment2"
                app:enterAnim="@anim/fragment_fade_enter"
                app:exitAnim="@anim/fragment_fade_exit"
                app:popUpTo="@id/fragment1" />
    </fragment>
</navigation>

这就是我在Fragment1-Class的代码中触发导航的方式:

 viewModel.itemSelected.observe(viewLifecycleOwner) {
        navigate(it)
    }

....

fun navigate(id: Long){
    val bundle = Bundle()
    bundle.putLong("itemid", id)    
    getNavController().navigate(R.id.action_fragment1_to_fragment2, bundle)

]

编辑: 更正了XML中的startDestination。

Edit2: 添加了更多代码。

1 个答案:

答案 0 :(得分:1)

您正在使用LiveData进行事件。 LiveData始终会缓存设置的值,因此,当您返回Fragment1时,您会再次观察LiveData并再次获得相同的值,从而再次导航(

)。

有关更多信息和替代方法,请参见this blog post