Register now for Android Dev Summit 2019!

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:

Kotlin

val finalHost = NavHostFragment.create(R.navigation.example_graph)
supportFragmentManager.beginTransaction()
    .replace(R.id.nav_host, finalHost)
    .setPrimaryNavigationFragment(finalHost) // this is the equivalent to app:defaultNavHost="true"
    .commit()

Java

NavHostFragment finalHost = NavHostFragment.create(R.navigation.example_graph);
getSupportFragmentManager().beginTransaction()
    .replace(R.id.nav_host, finalHost)
    .setPrimaryNavigationFragment(finalHost) // this is the equivalent to app:defaultNavHost="true"
    .commit();

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:

Kotlin

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(R.id.my_graph) { factory }

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

Java

ViewModelProviderFactory factory = ...
ViewModelStore store = navController.getViewModelStore(R.id.my_graph);
MyViewModel viewModel = new ViewModelProvider(store, factory);

For more information about ViewModel, see ViewModel Overview.