Home > Software engineering >  How can i Skip fragments when going D to A on backpressed?
How can i Skip fragments when going D to A on backpressed?

Time:08-09

Hey I am working on an application where I m using 6 fragments now when on the back button I want to skip all the other fragments like when I am on the 6th fragment(the last fragment) and the user presses the back button I want to go to fragment one directly without going through the other fragments like 6->1. I am new to android please guide me on how can I achieve that.

CodePudding user response:

If you're using the Navigation library, when you create an action that navigates you to Fragment 6, you can use the popUpTo attribute to clear the backstack up to Fragment 1. That way, when you go to 6, hitting the back button will take you to 1.


If you're doing things by hand with FragmentTransactions, when you add Fragment 1 to the container you should call addToBackStack("Fragment 1") (or some other name to represent that state, "top level" or something). Then you can use popBackStack("Fragment 1", 0) to undo any transactions that happened after that, basically walking back to where you displayed Fragment 1.

If you're doing that, you'll have to intercept the back button handling in Fragment 6 so you can call that popBackStack method, instead of just letting it pop the top state off. Here's how you're meant to handle that.

Another thing you could try is doing the popBackStack call inside the FragmentTransaction that goes from 5 to 6, popping everything back to 1 before you add Fragment 6 and then call addToBackStack (so you're basically backtracking to 1, then adding one step that takes you to 6, so there's only one step back to 1). I haven't tried that, but it should work I think!

It's honestly a lot easier to just use the Navigation library, it takes care of this kind of wrangling for you

  • Related