Navigation Components addOnDestinationChangedListener inspect stack and get count

Viewed 159

The common way to setup a bottom nav to show or hide is with addOnDestinationChangedListener as shown in the docs here: https://developer.android.com/guide/navigation/navigation-ui#listen_for_navigation_events

A problem I have encountered is the above logic says anything X id we should show the bottom navigation. But I want to allow the same fragment be open via a deeplink or from deep within a bottom navigation without the bottom navigation showing. So how I would think to do this is only show the bottom nav if the number of destinations in the stack are 1 or 2.

There is no way to get the stack count correctly from addOnDestinationChangedListener that I have found. So it seems explicitly Nav Components tries to hide the stack from access outside of the library. So navControlle.backstack is set as a library function.

Below are the things I have tried:

  • destination.graph with parent but it seems nav components only ever has parent and current nav graph and parent?.parent does not seem to return data.
  • navController hides the stack so the only way is to access previousBackStackEntry or currentBackStackEntry which does not give the previous previous which is what I need.
  • supportFragmentManager from activity with supportFragmentManger?.findFragmentById( R.id.nav_host_fragment )?.childFragmentManager?.backStackEntryCount It does not work because the above does get updated in time for destinationChangeListener so it's not accurate. It seems to be +-1 of what it should be because of race conditions.
  • navHostFrag.childFragmentManager.addOnBackStackChangedListener instead of addOnDestinationChangedListener but the problem here is this is not called on every navigation destination change.

Anyone able to inspect the stack via navigation components from addOnDestinationChangedListener

0 Answers
Related