How to delete a specific fragment from back stack in android

nihasmata picture nihasmata · Jul 3, 2015 · Viewed 42.7k times · Source

I have a problem about removing a specific fragment from back stack.My scenario is like this.Fragment-1 is replaced with Fragment-2 and then Fragment-2 is replaced with Fragment-3.

Calling order; Fragment-1-->Fragment-2-->Fragment-3.

When Fragment-3 is on the screen and then back button is clicked, i want to go

Fragment-1.That means i want to delete Fragment-2 from back stack.

How to do this ?

Answer

Ilario picture Ilario · Jul 3, 2015

In the backstack you don't have Fragments, but FragmentTransactions. When you popBackStack() the transaction is applied again, but backward. This means that (assuming you addToBackStackTrace(null) every time) in your backstack you have

1->2
2->3

If you don't add the second transaction to the backstack the result is that your backstack is just

1->2

and so pressing the back button will cause the execution of 2->1, which leads to an error due to the fragment 2 not being there (you are on fragment 3).
The easiest solution is to pop the backstack before going from 2 to 3

//from fragment-2:
getFragmentManager().popBackStack();
getFragmentManager().beginTransaction()
   .replace(R.id.container, fragment3)
   .addToBackStack(null)
   .commit();

What I'm doing here is these: from fragment 2 I go back to fragment 1 and then straight to fragment 3. This way the back button will bring me again from 3 to 1.