Navigate up by back button with Navigation Component

穿精又带淫゛_ 提交于 2021-02-13 17:34:25

问题


I use navigation components to navigate from one fragment to another. However, when the user press the back button, I want to navigate back to first fragment. But it keep showing the second fragment. This is my 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>

And this is how I trigger the navigation in the code of my 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)

]

Edit: Corrected startDestination in XML.

Edit2: Added more code.


回答1:


You're using a LiveData for an event. LiveData always caches the set value, so when you return to your Fragment1, you observe the LiveData again and get the same value a second time, causing you to navigate() yet again.

See this blog post for more information and alternatives.



来源:https://stackoverflow.com/questions/60176673/navigate-up-by-back-button-with-navigation-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!