问题
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
回答1:
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
回答2:
I understand that the answer is late. But may be it will help someone else.
val navHostFragment = supportFragmentManager.findFragmentById(R.id.navDrawerActivity)
val backStackEntryCount = navHostFragment?.childFragmentManager?.fragments?.size
<fragment
android:id="@+id/navDrawerActivity"
android:name="androidx.navigation.fragment.NavHostFragment"
app:navGraph="@navigation/nav_item"
app:defaultNavHost="true"
/>
回答3:
using addToBackStack() method during transaction you can solve your problem,
FragmentTransaction tx = fragmentManager.beginTransation();
tx.replace( R.id.fragment, new MyFragment() ).addToBackStack( "tag" ).commit();
//You need to add the following line for this solution to work;
fragment.getView().setFocusableInTouchMode(true);
fragment.getView().requestFocus();
fragment.getView().setOnKeyListener( new OnKeyListener(){
@Override
public boolean onKey( View v, int keyCode, KeyEvent event )
{
if( keyCode == KeyEvent.KEYCODE_BACK )
{
return true;
}
return false;
}
} );
来源:https://stackoverflow.com/questions/52481786/get-backstack-status-using-android-navigation-component