I have a scenario where fragment0 contains a NavHost, and I dynamically set its navigation graph to include the flow fragmentA -> fragmentB -> fragmentC. Additionally, fragment0 is part of a higher level navigation graph where the flow is fragment0 -> fragment1.
The issue arises when navigating from fragment0 to fragment1 and then returning to fragment0 by pressing back. At this point, the state of the NavHost within fragment0 is not retained; for instance, I might expect to see fragmentB in the NavHost of fragment0 because that was the state before navigation to fragment1. Instead it gets reseted to its initial state.
Upon investigation, I found that dynamically setting the nav graph of fragment0 in its onViewCreated callback is problematic. It seems that when navigating back from fragment1 to fragment0, the onViewCreated callback is triggered again, causing the NavHost state to be lost.
I’ve searched across the web to find what’s the best practice for dynamically setting nav graphs within fragments, but I haven’t found answer. Can anyone who faced a similar issue help on this? What’s the best stage of the Fragment lifecycle to set a graph dynamically without losing the previous state of inner NavHost?
I am sharing a picture to explain visually the scenario. Hope it helps
Here is how I dynamically set its navigation graph to include the flow fragmentA -> fragmentB -> fragmentC
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val navHostFragment = childFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val navGraph = navController.navInflater.inflate(R.navigation.nav_of_fragment0)
navController.graph = navGraph
}