1

I want to implement a dynamic fragment stack. More specificaly for example assume the following stack:

A -> B -> C -> D

It is possible that B will be added again after D. If that happens I want to remove B so that the result will be:

A -> C -> D -> B

I tried to do that like this:

void loadFragment(MyFragment f){
    FragmentManager fm = getSupportFragmentManager();
    MyFragment foundFragment = (MyFragment ) fm.findFragmentByTag(f.getClass().getName());
    if(foundFragment!=null) { 
        fm.popBackStack(f.getTransactionId(), 0);
    }
    String tag = f.getClass().getName();
    f.setTransactionId(tag);
    fm.beginTransaction()
         .addToBackStack(tag)
         .replace(R.id.fragment_container, f, tag)
         .commit();
}

so I do :

loadFragment(A);
loadFragment(B);
loadFragment(A);
loadFragment(B);

ThenI hit back which lands me to A (everything ok so far)
Then I hit back again and it lands me to A again.(where did the second B go ???)
If i hit back again the activity closes because there are no more fragments to pop.

I can't explain this...

How can I achieve the desired behavior ?

Anonymous
  • 4,470
  • 3
  • 36
  • 67

1 Answers1

0

First you load fragment A.

Then you load fragment B. So now the back stack looks like A - B

No you try to load A again. But there is already a fragment with the same tag. So you popBackStack till last appearance of A ( and not including A). Then you load A. So your back stack now looks like A - A

Last, you load B. So now when you click on back, it shows A. And it show A again when you click on back.

nupadhyaya
  • 1,909
  • 1
  • 14
  • 14
  • from what i ve understood fm.popBackStack(f.getTransactionId(), 0); removes the specific fragment contrary to fm.popBackStack(f.getTransactionId(), POP_BACK_STACK_INCLUSIVE); which removes everything UP TO that fragment. Is that not correct? And if not how do I end up with B->A after the second loadFragment(A); – Anonymous Sep 24 '18 at 21:21