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:

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().