We all have used fragments in our app and wrote fragment transactions many times according to our needs. So, the navigation component is another way to handle transactions but it provides few other benefits too.

Some of them are:

  • Handling back action correctly by default
  • Default standard animations and transitions while switching between fragments
  • Passing data between fragments (this is also my favorite).

Okay, now let’s discuss how to integrate it into our app.

First, we’ve to add following dependencies in our app-level build.gradlefile:

def nav_version = "2.3.0"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

The recommended way to navigate between destinations is to use the Safe Args Gradle plugin. This plugin generates simple object and builder classes that enable type-safe navigation and argument passing between destinations. To add Safe Args to our project, include the following classpath in our top-level build.gradle file:

buildscript {
    repositories {
        google()
    }
    dependencies {
        def nav_version = "2.3.0"
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
    }
}

Also, add this line to our app or module’s build.gradle file:

apply plugin: "androidx.navigation.safeargs"

There are three main components that we need to understand:

  1. Navigation Graph(nav_graph.xml): It contains all the navigation-related information like the start destination fragment, paths, etc.
  2. NavHost: A container that displays those destinations defined in nav_grap.xml file.
  3. NavController: It manages the swapping of fragments within a NavHost.

If you want to avoid implementing it from scratch, Android Studio can help you to start. Just select the navigation template while creating a project or adding a new activity.

#navigation-component #androiddev #android #jetpack-compose #android-app-development

Understanding the Basics of Navigation Component
1.35 GEEK