Save the date! Android Dev Summit is coming to Sunnyvale, CA on Oct 23-24, 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:


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


NavHostFragment finalHost = NavHostFragment.create(R.navigation.example_graph);
    .replace(, finalHost)
    .setPrimaryNavigationFragment(finalHost) // this is the 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().