Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a specific fragment from back stack in android

Tags:

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 ?

like image 576
nihasmata Avatar asked Jul 03 '15 05:07

nihasmata


People also ask

How do I pop a specific fragment in Android?

You can add a tag to each fragment while adding them to the backstack and then popfragment from backstack till the fragment with the tag you want is not reached. If this is called from the activity which hosts the fragments, doesnot work.


2 Answers

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.

like image 183
Ilario Avatar answered Sep 22 '22 18:09

Ilario


I had a very similar scenario to yours, my solution was just checking the amount of backStack transactions that I had.

If the transactions where more than 0 then I would simply pop it right away so it would skip it when pressing back.

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {         getSupportFragmentManager().popBackStackImmediate(); } ... fragmentTransaction.replace(R.id.main_fragment, newFrag, MAIN_FRAGMENT_TAG); fragmentTransaction.addToBackStack(null); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); fragmentTransaction.commit(); 

This would successfully:

  • A -> B (back pressed) -> back to A

  • A -> B -> C (back pressed) -> back to A

The only downside that I see is that there is a quick flash where fragment A is displayed before going to fragment C.

like image 22
Iv4n Avatar answered Sep 19 '22 18:09

Iv4n