TootsieRockNRoll
TootsieRockNRoll

Reputation: 3288

Android Jetpack navigation A ->B->C->A

I couldn't find anything online so here I am. I'm using the jetpack navigation component and I want to navigate from fragmentA to fragmentB, and then fragmentB will navigate to fragmentC, but when pressing hw back button I want to go back straight to fragmentA. is this possible with the current release?

Upvotes: 3

Views: 372

Answers (2)

musooff
musooff

Reputation: 6852

This can be done with adding popUpTo to your action where you move from B -> C.

<fragment
    android:id="@+id/fragmentB"
    android:name="com.ballboycorp.anappaday.navigationtest.FragmentB"
    android:label="fragment_b"
    tools:layout="@layout/fragment_b">
    <action
        android:id="@+id/action_fragmentB_to_fragmentC"
        app:destination="@+id/fragmentC"
        app:popUpTo="@+id/fragmentA" />
</fragment>

What that means is

From B move to C and when user clicks back button, move back to A.

You should navigation to C using that action instead of giving destination id.

button.setOnClickListener {
    findNavController().navigate(R.id.action_fragmentB_to_fragmentC)
}

Visually this is how it looks

enter image description here

Upvotes: 3

apksherlock
apksherlock

Reputation: 8371

With the Navigation Component you can handle onBackPressed on fragments. In your onViewCreated of fragment C just add this line of code:

requireActivity().onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                view.findNavController().popBackStack(R.id.fragmentA, false)
            }
        })

Upvotes: 0

Related Questions