Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

android - Navigate up by back button with Navigation Component

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...