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

Can nested NavHosts both be the default nav host (defaultNavHost="true")?


I implemented a navigation structure using two nested NavHostFragmentss. I want the back button to first pop the navigation stack of the child Fragment's navigation graph, and then once back to the start, pop the parent Fragment's graph. This behaviour works when I set app:defaultNavHost="true" for both the parent and child FragmentContainerViews.

But according to the Android documentation:

The app:defaultNavHost="true" attribute ensures that your NavHostFragment intercepts the system Back button. Note that only one NavHost can be the default. If you have multiple hosts in the same layout (two-pane layouts, for example), be sure to specify only one default NavHost.

Is this rule still applicable when using nested NavHosts? What problems could I run into when setting defaultNavHost="true" for multiple/nested NavHosts?


Solution

  • Yes, the limitation of 'only one defaultNavHost' only applies to two NavHostFragments in the same FragmentManager (i.e., siblings). Nesting them is totally fine.