Is there a way to remove all fragments which are already added the specific view with its view id?
For example I want to remove all fragments which is added into R.id.fragmentcontainer view.
Explanation: MainFragment -> Fragment A -> Fragment B (this is added to backstack) -> Fragment C -> MainFragment (clear backstack ).
To remove a fragment from the host, call remove() , passing in a fragment instance that was retrieved from the fragment manager through findFragmentById() or findFragmentByTag() . If the fragment's view was previously added to a container, the view is removed from the container at this point.
Its very simple just loop through all the fragments and remove it
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
But in case of Navigation Drawer be sure to check it, if you try to remove it you will get error.
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment instanceof NavigationDrawerFragment) {
continue;
}
else {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
Last but very important be sure to check for null before doing any fragment transactions
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment instanceof NavigationDrawerFragment) {
continue;
}
else if (fragment != null) {
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
}
}
In case someone is looking for a code in Kotlin:
supportFragmentManager.apply {
for (fragment in fragments) {
beginTransaction().remove(fragment).commit()
}
popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
}
It is indeed very simple.
private static void removeAllFragments(FragmentManager fragmentManager) {
while (fragmentManager.getBackStackEntryCount() > 0) {
fragmentManager.popBackStackImmediate();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With