Search code examples
androidandroid-fragmentsandroid-architecture-navigation

Killing Fragment in Navigation Components without going previous fragment


I have two fragments (like following code). After I switched from 1st Fragment to 2nd fragment when I clicked back button it's going back to 1st fragment and I don't want to be.

Here my code nav_graph

<navigation>
  <fragmentone>
    <action
      destination= fragmenttwo/>
  </fragmentone>
  <fragmenttwo>
  </fragmenttwo>
</navigation>

How can navigate 2nd fragment like we used to change Activity with finish();


Solution

  • Exiting an app or (Finishing the navigation components activity) doesn't differ much from the traditional way, but what you need to catch is the back press button event on that fragment that you want to finish the activity on.

    As per documentation, the current valid way to catch the back pressed button is to use OnBackPressedDispatcher, here is a demo:

    On the 2nd fragment, register OnBackPressedDispatcher and handle finishing the activity on the handleOnBackPressed() callback:

    requireActivity().onBackPressedDispatcher.addCallback(
        viewLifecycleOwner,
        object : OnBackPressedCallback(true) {
            override
            fun handleOnBackPressed() {
    
                // findNavController().popBackStack() // Popup to the first destination fragment
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    requireActivity().finishAndRemoveTask()
                } else {
                    requireActivity().finish()
                }
            }
        })
    

    Note: You can use findNavController().popBackStack() before finishing the activity, if you want to popup the back stack to the first destination fragment before finishing the activity, but this will show up the first fragment before the app exit which could be a behavior that not appeals to you.