Search code examples
androidandroid-architecture-componentsandroid-architecture-navigation

Get Backstack status using android navigation component


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


Solution

  • 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