I'm not sure I understand your question correctly. If you want to replace several fragments with a tag from the top of the backstack with one fragment with the same tag, you can use the following approach.
Instead of using tags to identify fragments, they set different backstack names for fragments of different types. You can still use the fragment tag, but that will not help in solving this particular problem. Then manually remove fragments from the stack one at a time until a fragment with a different backstack name appears at the top or without fragments.
public void addFragment(final int containerViewId, final Fragment fragment, final String backStackName, final boolean replace) { final FragmentManager fragmentManager = getSupportFragmentManager(); if (replace) { while (fragmentManager.getBackStackEntryCount() > 0) { final int last = fragmentManager.getBackStackEntryCount() - 1; final FragmentManager.BackStackEntry entry = fragmentManager.getBackStackEntryAt(last); if (!TextUtils.equals(entry.getName(), backStackName)) { break; } fragmentManager.popBackStackImmediate(); } } fragmentManager .beginTransaction() .replace(containerViewId, fragment) .addToBackStack(backStackName) .commit(); fragmentManager.executePendingTransactions(); }
Now, if you make the following calls, your backside will only contain fragment1 and fragment4 .
addFragment(R.id.container, fragment1, "D2", false); addFragment(R.id.container, fragment2, "D1", false); addFragment(R.id.container, fragment3, "D1", false); addFragment(R.id.container, fragment4, "D1", true);
UPDATE
In this particular case, the following code was enough:
getSupportFragmentManager().popBackStack( backStackStateName, FragmentManager.POP_BACK_STACK_INCLUSIVE); getSupportFragmentManager() .beginTransaction() .replace(containerViewId, fragment, fragmentTag) .addToBackStack(backStackStateName) .commit();
https://github.com/tuxmobil/CampFahrplan/pull/148