How to use Navigation component in an Android app?

The Navigation component is part of Android Jetpack and simplifies navigation within your app, enabling developers to manage app navigation in a consistent manner. It provides an easy way to handle fragment transactions, deep linking, and passing data between destinations.

Setting Up the Navigation Component

To use the Navigation component in your Android app, follow these steps:

  1. Add the Navigation dependency to your project’s build.gradle file:
dependencies { def nav_version = "2.3.5" // Check for the latest version implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" implementation "androidx.navigation:navigation-ui-ktx:$nav_version" }
  1. Create a Navigation graph. Right-click on the res directory, select New > Android Resource File, and name it nav_graph.xml. Choose the Navigation resource type.
  2. Define your destinations (fragments) in the nav_graph.xml file using the graphical editor.
  3. In your activity layout file, include a NavHostFragment that displays your fragment destinations:
  1. Set up the NavController in your Activity:
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController);

Performing Navigation

You can navigate between destinations easily using the following methods:

navController.navigate(R.id.action_firstFragment_to_secondFragment);

To handle up navigation, override onSupportNavigateUp in your Activity:

@Override public boolean onSupportNavigateUp() { return NavigationUI.navigateUp(navController, null) || super.onSupportNavigateUp(); }

Navigation Component Android Jetpack Android Navigation Android Fragments NavController NavHostFragment