Search code examples
androidandroid-jetpackandroid-architecture-navigationandroid-jetpack-navigation

Removing a fragment from backstack with a dynamic navGraph startDestination


I have an Activity with a navGraph that conditionally chooses a startDestination when the the Activity is created.

     private suspend fun checkStatusAndNavigate(userID: Int) {
        val navController = findNavController(nav_host_container)
        val user = getUserFromDB(userID)
        val dateNow = Date((if (prefSaved) prefTime() else System.currentTimeMillis())
        val navGraph = navController.navInflater.inflate(nav_graph).apply {
            // NavGraph inflates with one of three possible starting points: A, B, or C.
            startDestination = when {
                checkDate(dateNow) == DateCheck.OldDate -> R.id.fragment_a
                !user.hasOptedIn -> R.id.fragment_b
                else -> R.id.fragment_c
            }
        }
        navController.setGraph(navGraph)
    }

After navController.setGraph(navGraph), the startDestination is launched. This works as expected.

Fragment B's only destination out is to Fragment C. But when the user is in Fragment C and does onBackPressed(), I would like to skip Fragment B, and return to whatever called the Activity (there are a few options, so overriding onBackPressed isn't a great option).

I don't think this is a popTo or popToInclusive problem. I don't want to clear the backstack. I just want to keep Fragment B from ever entering the backstack if at all possible.


Solution

  • If you don't want B to be accessible on back from C, then you're supposed to create an Action that is popTo=B, popToInclusive=true, and destination=C.