pop specific fragment from stack and remove others pop specific fragment from stack and remove others android android

pop specific fragment from stack and remove others


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.

FragmentManager fm = getFragmentManager();for (int i = fm.getBackStackEntryCount() - 1; i > 0; i--) {    if (!fm.getBackStackEntryAt(i).getName().equalsIgnoreCase(tagname)) {        fm.popBackStack();    }    else    {     break;    }}


You can call the function below while you are in Fragment E:

getFragmentManager().popBackStack("tag", 0);

Here the tag is string passed as tag while adding fragment B to backstack.


If you are using AndroidX navigation, you can use the following:

findNavController().popBackStack(R.id.FragmentB, false)