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

How to know the number of fragment that are in stack when using Navigation Component?


I'm using Navigation Components in my app. From the fist fragment to the last one there are also other fragments, for instance nice. Everytime a user clicks on a fragment is added to the stack. How can I know how many fragments are already added to the stack at one point in time?


Solution

  • You can use below method in Activity to get current backstackentry count, where home_nav_host_fragment is id of your container NavHostFragment in activity.

    public int getStackCount(){
    NavHostFragment navHostFragment = (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.home_nav_host_fragment);
    int backStackEntryCount = navHostFragment.getChildFragmentManager().getBackStackEntryCount();
    return backStackEntryCount;
    }
    

    to call this method from fragment you can use
    int count = ((YourActivity)getActivity()).getStackCount();