使用导航组件通过后退按钮向上导航
Navigate up by back button with Navigation Component
我使用导航组件从一个片段导航到另一个片段。但是,当用户按下后退按钮时,我想导航回第一个片段。但它一直显示第二个片段。这是我的 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
编辑2:
添加了更多代码。
您正在为事件使用 LiveData。 LiveData 始终缓存设置值,因此当您 return 到您的 Fragment1 时,您再次观察 LiveData 并第二次获得相同的值,导致您再次 navigate() 。
有关更多信息和备选方案,请参阅 this blog post。
我使用导航组件从一个片段导航到另一个片段。但是,当用户按下后退按钮时,我想导航回第一个片段。但它一直显示第二个片段。这是我的 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编辑2: 添加了更多代码。
您正在为事件使用 LiveData。 LiveData 始终缓存设置值,因此当您 return 到您的 Fragment1 时,您再次观察 LiveData 并第二次获得相同的值,导致您再次 navigate() 。
有关更多信息和备选方案,请参阅 this blog post。