[英]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。
Edit2:添加了更多代碼。
您正在將 LiveData 用於事件。 LiveData 總是緩存設置的值,所以當你返回到你的 Fragment1 時,你再次觀察 LiveData 並第二次獲得相同的值,導致你再次導航()。
有關更多信息和替代方案,請參閱此博客文章。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.