Skip to content

Android Navigation component example

2. Android Navigation component example

1. Overview

In this article, we will see an example of the Android Navigation component. However, for a high-level overview of the concepts, refer to the Android Navigation component article.

2. Android Navigation component example

For example, we will create two fragments: FirstFragment and SecondFragment. Whenever we click on the “Load” button of the first fragment, the Navigation component will load the SecondFragment on the screen.

Also, when you press the back button from SecondFragment, the previous FirstFragment will load.

Here, Main Activity will be the container to load these fragments. This project is available on GitHub for download and use.

2.1. Set up Android navigation component example

1. Android navigation component requires Android Studio 3.3 or higher

2. Add Java 8 feature to your project:

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}
android {
    ...
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

3. Add the required dependencies to your app’s build gradle file.

dependencies {
  def nav_version = "2.3.5"


  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"


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


  implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"


  androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"


  implementation "androidx.navigation:navigation-compose:2.4.0-alpha10"
}
dependencies {
  val nav_version = "2.3.5"


  implementation("androidx.navigation:navigation-fragment:$nav_version")
  implementation("androidx.navigation:navigation-ui:$nav_version")


  implementation("androidx.navigation:navigation-fragment-ktx:$nav_version")
  implementation("androidx.navigation:navigation-ui-ktx:$nav_version")


  implementation("androidx.navigation:navigation-dynamic-features-fragment:$nav_version")


  androidTestImplementation("androidx.navigation:navigation-testing:$nav_version")


  implementation("androidx.navigation:navigation-compose:2.4.0-alpha10")
}

2.2. Add navigation component destinations to your Android project

Destinations are the screens, views, or places that you can navigate to. It includes the activities, fragments, and custom views. Thus, your fragments First Fragment and Second Fragment are your destinations here. So let’s add them to your project.

The FirstFragment contains a button “Load” and also displays a simple text “First Fragment” in the center of the screen.

FirstFragment Kotlin file
class FirstFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        load?.setOnClickListener {
            Navigation.findNavController(it).navigate(R.id.load_fragment)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onResume() {
        super.onResume()
    }
}

We have a click listener for the button “Load“. So on click of that button, we will request the Navigation controller to load the destination specified in the action load_fragment.

Don’t worry if you are not sure of what this action is. We will see it later in this article while adding the navigation graph.

First Fragment xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/first_fragment"
        android:layout_gravity="center"/>

    <Button
        android:id="@+id/load"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center"
        android:text="Load" />
</FrameLayout>

The second fragment doesn’t have any functionality, and it is just a blank fragment. It only displays a simple text “Second Fragment” on the screen.

Second Fragment Kotlin file
class SecondFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        return inflater.inflate(R.layout.fragment_second, container, false)
    }
}
Second Fragment xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SecondFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/second_fragment" />

</FrameLayout>

2.3. Add Android Navigation graph

The navigation graph is a new resource type added for the Android navigation component. You can open this navigation graph using the Navigation editor which is available from Android Studio 3.3 and above.

Navigation resource file
Navigation resource file

This navigation graph contains two destinations: First Fragment and Second Fragment. The First Fragment destination contains an action load_fragment.

The action contains an id which you can refer anywhere from your code. It also has the destination attribute that specifies the fragment destination to navigate.

If you remember, we have used this action inside the load button’s click listener of the First Fragment.

load?.setOnClickListener {
    Navigation.findNavController(it).navigate(R.id.load_fragment)
}

When we click on the button “Load” in the First Fragment, the Navigation controller uses this action load_fragment and navigates to the Second Fragment (destination mentioned in the action).

<?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"
    android:id="@+id/nav_type"
    app:startDestination="@id/firstFragment">
    <fragment
        android:id="@+id/firstFragment"
        android:name="com.tedblob.kotlin.navigationcomponentexample.FirstFragment"
        android:label="fragment_first"
        tools:layout="@layout/fragment_first" >
        <action
            android:id="@+id/load_fragment"
            app:destination="@id/secondFragment" />
    </fragment>
    <fragment
        android:id="@+id/secondFragment"
        android:name="com.tedblob.kotlin.navigationcomponentexample.SecondFragment"
        android:label="fragment_second"
        tools:layout="@layout/fragment_second" />
</navigation>

2.3. Add NavHostFragment

We should add the NavHostFragment to our Main Activity layout. It is a container that shows the fragments (Destinations) declared in the navigation graph.

<?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">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_type" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.tedblob.kotlin.navigationcomponentexample

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.Navigation

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

If you run the code, it will show the following experience.

Navigation Component example

3. Conclusion

To sum up, we have seen a simple example of the Android Navigation component.

3 thoughts on “Android Navigation component example”

  1. Pingback: Android navigation component multiple activities - TedBlob

  2. Pingback: Navigation component deep link example - TedBlob

  3. class FirstFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    load?.setOnClickListener {
    Navigation.findNavController(it).navigate(R.id.load_fragment)
    }
    }

    override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
    ): View? {
    return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onResume() {
    super.onResume()
    }
    }

    plz check this code

Leave a Reply

Your email address will not be published. Required fields are marked *