Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Navigation Component Tutorial

Introduction

The Navigation Component is a part of Android Jetpack that simplifies navigation within an app. It provides a consistent way to implement navigation in Android applications, making it easier to handle fragment transactions, manage back stack, and navigate between destinations.

Setup

Before you start using the Navigation Component, you need to add the necessary dependencies to your project's build.gradle files.

In your project-level build.gradle file:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "androidx.navigation:navigation-safe-args-gradle-plugin:2.3.5"
    }
}
                

In your app-level build.gradle file:

apply plugin: 'androidx.navigation.safeargs'

dependencies {
    def nav_version = "2.3.5"
    
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}
                

Creating the Navigation Graph

A navigation graph is a resource file that contains all the navigation-related information in one place. It defines the possible paths a user can take through your app.

To create a navigation graph:

  1. Right-click on the res folder in your project.
  2. Select New > Android Resource File.
  3. Name the file nav_graph, set the resource type to Navigation, and click OK.

Add destinations and actions in the nav_graph.xml file:

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name="com.example.app.HomeFragment"
        android:label="Home"
        tools:layout="@layout/fragment_home">
        <action
            android:id="@+id/action_homeFragment_to_detailFragment"
            app:destination="@id/detailFragment" />
    </fragment>

    <fragment
        android:id="@+id/detailFragment"
        android:name="com.example.app.DetailFragment"
        android:label="Detail"
        tools:layout="@layout/fragment_detail" />

</navigation>
                

Setting Up NavHostFragment

The NavHostFragment hosts the navigation graph and manages navigation within an activity.

Add a NavHostFragment to your activity's layout file:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:navGraph="@navigation/nav_graph" />

</androidx.constraintlayout.widget.ConstraintLayout>
                

Navigating Between Destinations

To navigate between destinations defined in your navigation graph, use the NavController class.

In your fragment, you can navigate using the following code:

button.setOnClickListener {
    findNavController().navigate(R.id.action_homeFragment_to_detailFragment)
}
                

Handling Up and Back Actions

The Navigation Component handles the up and back actions automatically. To support the up button in the action bar, configure it in your activity:

override fun onSupportNavigateUp(): Boolean {
    return findNavController(R.id.nav_host_fragment).navigateUp() || super.onSupportNavigateUp()
}
                

Using Safe Args

Safe Args is a Gradle plugin that generates type-safe classes for navigating and passing data between destinations.

To pass data between fragments:

  1. Define arguments in your navigation graph:
<fragment
    android:id="@+id/detailFragment"
    android:name="com.example.app.DetailFragment"
    android:label="Detail"
    tools:layout="@layout/fragment_detail">
    <argument
        android:name="itemId"
        app:argType="string" />
</fragment>
                

Navigate and pass data using generated classes:

val action = HomeFragmentDirections.actionHomeFragmentToDetailFragment(itemId)
findNavController().navigate(action)
                

Retrieve the data in the destination fragment:

val args: DetailFragmentArgs by navArgs()
val itemId = args.itemId
                

Conclusion

The Navigation Component simplifies the implementation of navigation in Android apps. By using a navigation graph, NavHostFragment, and NavController, you can manage navigation in a consistent and predictable way. Safe Args adds type safety to your navigation actions, reducing the risk of runtime errors. This tutorial covered the basics, but the Navigation Component also supports advanced features such as deep linking, nested graphs, and conditional navigation.