Search code examples
android-architecture-navigation

Android NavController get backstack


We use NavController.OnDestinationChangedListener and the provided parameter NavDestination to hide/show the bottom navigation bar (which is anchored in the root activity) depending on the current destination. But our logic requires also to know which was the previous destination for the current destination in order to hide/show the bottom navigation bar.

NavController.OnDestinationChangedListener also provides a NavController parameter, and NavController has an internal property called mBackStack which seems to be precisely what we need. So, is there a way to access the NavController backstack without using reflection?

Thanks!


Solution

  • There is a way to infer the NavDestination(s) which are currently in the backstack by accessing all the destinations in the graph and then calling navController.getBackStackEntry in each one of them.

    val destinationsInBackStack = navController.graph.mapNotNull { dest ->
        try {
            navController.getBackStackEntry(dest.id)
            dest
        } catch (e: IllegalArgumentException) {
            null
        }
    }