Create a navigation controller

The navigation controller is one of the key concepts in navigation. It holds the navigation graph and exposes methods that allow your app to move between the destinations in the graph.

When using the Navigation component, you create a navigation controller using the NavController class. NavController is the central navigation API. It tracks which destinations the user has visited, and allows the user to move between destinations. This guide demonstrates how to create a NavController in your app.

For information on how to add a navigation graph to your NavController, see Design your navigation graph. NavController provides a few different ways to navigate to the destinations in its graph. For more, see Navigate to a destination.

Compose

To create a NavController when using Jetpack Compose, call rememberNavController():

val navController = rememberNavController()

You should create the NavController high in your composable hierarchy. It needs to be high enough that all the composables that need to reference it can do so.

Doing so lets you to use the NavController as the single source of truth for updating composables outside of your screens. This follows the principles of state hoisting.

Views

If you are using the Views UI framework, you can retrieve your NavController using one of the following methods depending on the context:

Kotlin:

Java:

Typically, you first get a NavHostFragment, and then retrieve the NavController from the fragment. The following snippet demonstrates this:

Kotlin

val navHostFragment =
    supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController

Java

NavHostFragment navHostFragment =
    (NavHostFragment) getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
NavController navController = navHostFragment.getNavController();

Further reading

  • Design your navigation graph: A guide detailing how to add a graph to your NavController that contains all the destinations in your app.
  • Navigate to a destination: A guide detailing how to use the NavController to move between destinations in your navigation graph.