Home > Net >  Android - NavGraph without a startDestination
Android - NavGraph without a startDestination

Time:04-19

How can I have a navGraph without a startDestination?

I have a BottomSheet fragment container. When some events are triggered I want to expand this BottomSheet and load a fragment to its fragment container. Until one of those events are triggered I don't want the fragment container to have any fragment loaded. I want it to be empty.

But if don't supply a valid startDestination to the navGraph the app crashes with the exception:

IllegalStateException: no start destination defined

Is this possible? What would be the best way to handle this?

EDIT

I know I can supply a startDestination programmatically. But this is not a graceful approach. It introduces clutter code that needs to be executed when the first fragment load needs to happen and it gets worse when that fragment needs arguments.

The goal is to skip supplying a startDestination altogether.

CodePudding user response:

First solution: Create empty fragment and set it as startDestination in graph

Second solution: Wait until event triggered and open BottomSheet with startDestination argument. Read argument of BottomSheet and change start destination

navGraph.setStartDestination(R.id.fragment2)

CodePudding user response:

Set a default startDestination in your navgraph. For me, for example, it is the destination I usually want to start with (R.id.trips_fragment)

Then, in my activity onCreate:

private fun setupMainNavigationGraph() {
    val navController = findNavHostFragment().navController
    val mainNavigationGraph = navController.navInflater.inflate(R.navigation.main_graph)
    mainNavigationGraph.setStartDestination(intent.getIntExtra(START_DESTINATION_INTENT_EXTRA, R.id.trips_fragment))
    navController.graph = mainNavigationGraph
}

This way, if I want to use a custom start destination, I pass the start destination ID as an Intent to the activity, and the graph is loaded with the overridden start destination.

Note, the line here

intent.getIntExtra(START_DESTINATION_INTENT_EXTRA, R.id.trips_fragment)

R.id.trips_fragment is the default value.

I use this for integration tests to override the start destination.

  • Related