Interact programmatically with the Navigation component

The Navigation component provides ways to programmatically create and interact with certain navigation elements.

Create a NavHostFragment

You can use NavHostFragment.create() to programmatically create a NavHostFragment with a specific graph resource, as shown in the example below:


val finalHost = NavHostFragment.create(R.navigation.example_graph)
    .replace(, finalHost)
    .setPrimaryNavigationFragment(finalHost) // equivalent to app:defaultNavHost="true"


NavHostFragment finalHost = NavHostFragment.create(R.navigation.example_graph);
    .replace(, finalHost)
    .setPrimaryNavigationFragment(finalHost) // equivalent to app:defaultNavHost="true"

Note that setPrimaryNavigationFragment(finalHost) lets your NavHost intercept system Back button presses. You can also implement this behavior in your NavHost XML by adding app:defaultNavHost="true". If you're implementing custom Back button behavior and don't want your NavHost intercepting Back button presses, you can pass null to setPrimaryNavigationFragment().

Starting with version 2.1.0-alpha02, you can create a ViewModel that's scoped to a navigation graph, enabling you to share UI-related data between the graph's destinations. Any ViewModel objects created in this way live until the associated NavHost and its ViewModelStore are cleared or until the navigation graph is popped from the back stack.

The following example shows how to retrieve a ViewModel that's scoped to a navigation graph:


In Kotlin, you can use the navGraphViewModels() property delegate to retrieve a ViewModel from within a fragment destination:

val factory: ViewModelProviderFactory = ...
val viewModel: MyViewModel
    by navGraphViewModels( { factory }

Note that in this example, by navGraphViewModels() automatically calls findNavController() to retrieve the associated NavController.


ViewModelProviderFactory factory = ...

NavBackStackEntry backStackEntry = navController.getBackStackEntry(;

// NavBackStackEntry implements ViewModelStoreOwner,
//  so we can pass it to ViewModelProvider directly
MyViewModel viewModel = new ViewModelProvider(backStackEntry, factory).get(MyViewModel.class);

For more information about ViewModel, see ViewModel Overview.