how I can pop specific fragment from stack and remove others from a fragment? for example these are my fragments and I\'m in E right know.
A-> B -> C -> D ->E
<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;
}
}
If you are using AndroidX navigation, you can use the following:
findNavController().popBackStack(R.id.FragmentB, false)
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
.
tldr: try using fragmentManager instead of supportFragmentManager if the code doesn't work
solution: fragmentManager.popBackStackImmediate(tagName, 0)
I know it's an old question but after spending a few hours on this, I wasn't able to get close to the desired result.
I was using supportFragmentManager and the code was:
supportFragmentManager.popBackStackImmediate(tagName, 0)
but it wasn't working as intended neither according to what was written in the documentation. Just as a fluke I thought about using the fragmentManager instead of the supportFragmentManager and voila, it worked!
So for anyone stuck on this, maybe give this a try.
Use following code for pop back stack entry:
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}else {
super.onBackPressed();
}