Prevent The Same Fragment From Stacking More Than Once ( addToBackStack)

Ivan Javorovic picture Ivan Javorovic · Nov 17, 2015 · Viewed 7.2k times · Source

I have an Activity with three Fragments lets call them A, B and C. Fragment A is called in the Activity onCreate().

FragmentA fragA = new FragmentA();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.activity2_layout, fragA, "A");
transaction.commit();

And gets replaced with Fragment B or C when certain buttons are pressed, and the FragmentTransaction calls addToBackStack().

FragmentB fragB = new FragmentB(); //or C
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.activity2_layout, fragB, "B");  //or C
transaction.addToBackStack("B"); //or C
transaction.commit();

But lets say I call Fragment B three times in a row, how can I prevent it from stacking on to it self? And at the same time I want this to be possible: B called > C called > B called - BUT when i try to go back I want B to be opened only once ( C < B) instead of (B < C < B). So basically removing the first backStack with the new one.

Answer

Abu Ruqaiyah picture Abu Ruqaiyah · Nov 18, 2015

From How to resume Fragment from BackStack if exists, which maybe very similar to your query.

There is a way to pop the back stack based on either the transaction name or the id provided by commit (for eg. using the Fragment's class name as Thijs already mentioned):

String backStateName = fragment.getClass().getName();

Adding to backstack:

FragmentTransaction ft = manager.beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(backStateName);
ft.commit();

When popping:

getSupportFragmentManager().popBackStackImmediate (backStateName, 0); 

So before replacing fragment, we can check existance in backstack like:

boolean fragmentPopped = manager.popBackStackImmediate (backStateName, 0);

if (!fragmentPopped){ //fragment not in back stack, create it.
    ...
    ...
    ft.addToBackStack(backStateName);
    ft.commit();
}

Please check the above question and the accepted answer for more explanation.