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 ?