Search code examples
androidkotlinandroid-navigation-graph

Android navigation graph add extra fragment to stack on navigation


Solution: both the accepted answer and the comment from @ianhanniballake work. Due to the simplicity of the comment i'm going to use the comment one! Solution:

I am trying the following:

There a three fragments in the navigation graph
1: dashboard (start)
2: list with items
3: item details

The user can navigate from 1 to 2 or directly from 1 to 3 for a couple of items. if the user goes from 1 to 3 I would like to go back to 2 first.

So, for example:

> means going forward in the stack

< means going backward in the stack

case1: when going to list first
1 > 2 > 3 < 2 < 1

case2: when going directly to the details
1 > 3 < 2 < 1

Is something like this possible?

Thanks!


Solution

  • This can be done by overriding the back implementation which can be found here, and returning to the fragment you wish when back is pressed.

    I would create a new navigation action starting from Fragment3 going to Fragment2. Make sure to select popToInclusive on this action. Then inside Fragment3 do the following to ensure that when back is pressed, Fragment2 will always be shown when navigating back in Fragment3:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        val callback: OnBackPressedCallback =
                object : OnBackPressedCallback(true) {
                    override fun handleOnBackPressed() {
                        // Handle the back button event
                        findNavController().navigate(Fragment3FragmentDirections.actionFragment3ToFragment2())
                    }
                }
        requireActivity().onBackPressedDispatcher.addCallback(this, callback)
    }