I want to implement backpress behaviour such that it prompts a confirmation popup when you press back with the backstack empty, otherwise it pops the next fragment in the stack.
I'm trying to get the backstack count, but i always get 0 from both fragment managers
getSupportFragmentManager().getBackStackEntryCount();
getFragmentManager().getBackStackEntryCount();
I guess it should work since i checked the google code of fragment navigator and it adds to backstack through the canonical fragment transaction:
FragmentNavigator.java:
if (initialNavigation || isClearTask) {
backStackEffect = BACK_STACK_DESTINATION_ADDED;
} else if (isSingleTopReplacement) {
// Single Top means we only want one instance on the back stack
if (mBackStack.size() > 1) {
// If the Fragment to be replaced is on the FragmentManager's
// back stack, a simple replace() isn't enough so we
// remove it from the back stack and put our replacement
// on the back stack in its place
mFragmentManager.popBackStack();
ft.addToBackStack(Integer.toString(destId));
mIsPendingBackStackOperation = true;
}
backStackEffect = BACK_STACK_UNCHANGED;
} else {
ft.addToBackStack(Integer.toString(destId));
mIsPendingBackStackOperation = true;
backStackEffect = BACK_STACK_DESTINATION_ADDED;
}
ft.setReorderingAllowed(true);
ft.commit();
I didn't find any API to retrieve this information through NavController or Navigator neither.
Thanks
To retrieve the NavController for a fragment, activity, or view, use one of the following methods: Kotlin: Fragment. findNavController()
How do I get rid of current fragment navigation component? You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods: FragmentManager manager = getActivity(). getSupportFragmentManager();
Use Up or Back button to go to a previous step of the order flow.
navigateUp() Attempts to navigate up in the navigation hierarchy. boolean.
May be help to someone too:
<fragment
android:id="@+id/YOUR_NAVIGATION_HOST_ID"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:defaultNavHost="true"
app:navGraph="@navigation/YOUR_NAVIGATION_HOST" />
val navHostFragment = supportFragmentManager.findFragmentById(R.id.YOUR_NAVIGATION_HOST_ID)
val backStackEntryCount = navHostFragment?.childFragmentManager?.backStackEntryCount
To check the back stack count of a navigation host fragment, you should use childFragmentManager of navHostFragment :
navHostFragment.childFragmentManager.addOnBackStackChangedListener {
if (navHostFragment.childFragmentManager.backStackEntryCount == 0) {
// First fragment is open, backstack is empty
} else {
// there are fragments in backstack
}
}
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