Home > Software design >  Killing Fragment in Navigation Components without going previous fragment
Killing Fragment in Navigation Components without going previous fragment

Time:10-10

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();

CodePudding user response:

In design tab you will see a pop behavior section

pop_behavior

in pop upto, select fragment 1

in pop up to inclusive, select true

CodePudding user response:

Exiting an app or (Finishing the navigation components activity) doesn't differ much in 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 to the back stack to the first destination fragment before finishing the activity, but this will show up the first fragment before the app exist which could be a behavior that not appeals to you.

  • Related