3 fragments:
- FragmentA: root fragment (implementing IRootFragment), opening by BottomNavigationView;
- FragmentB: opening from A-fragment by button;
- FragmentC: opening from B-fragment by button;
I can go to A-fragment from C-fragment by BottomNavigationView and i have to clear back stack, but dont know, why it's not working. When I moved from the first fragment to the second and press the button back, the fragments overlap each other and only after that it exits the application.
If i go C -> B -> A by back button and press the back button, all works good.
Code for opening fragments:
fragmentManager
.beginTransaction()
.replace(R.id.fl_container, new FragmentA())
.commit();
fragmentManager
.beginTransaction()
.replace(R.id.fl_container, new FragmentB())
.addToBackStack(null)
.commit();
fragmentManager
.beginTransaction()
.replace(R.id.fl_container, new FragmentC())
.addToBackStack(null)
.commit();
BackPressed:
Fragment fragment = fragmentManager.findFragmentById(R.id.fl_container);
if (fragment instanceof IRootFragment) {
if (fragmentManager.getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack(
fragmentManager.getBackStackEntryAt(0).getId(),
FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
super.onBackPressed();
} else {
fragmentManager.popBackStackImmediate();
}
I'm trying all of this: Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?
fragmentManager.getBackStackEntryCount() always > 0