Open In App

Overview of Navigation in Android Architecture Components

Last Updated : 15 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Navigation basically in mobile development refers to the interaction between different screens or pieces of contents within the application. Android Jetpack’s architecture Component the Navigation is so powerful, providing a consistent and predictable user experience. The navigation component helps to implement the Navigation between activities and fragments or chunks of the data in the application by simple button clicks. In this article, it’s been discussed from Navigation key properties to implementing sample Navigation between the fragments.

Three key properties of Navigation are:

  1. Navigation Graph: This is the XML file containing all of the individual content areas, within the applications called destinations. These may be possible paths that users may take through the application.
  2. NavHost: This is the XML file which is an empty container that displays the destinations as the user navigates, an. This basically contains the NavHostFragment, which displays the various destinations from Navigation Graph.
  3. NavController: NavController is an object which manages the navigation of destinations with NavHost. This controls the swapping of destination content as the user navigates through the destinations through the application.

Benefits that developers get from Navigation Component are:

  • Navigation Component handles the Fragment transaction.
  • Handling Up and back actions, basically handling the Backstack.
  • Provides standardized animation and transitions while switching the content of the NavHost.
  • Easy handling and implementation of deep linking.
  • Easy handling and implementation of Navigation UI patterns such as Navigation Drawer or Bottom Navigation Views etc.
  • Safe Args, a Gradle plugin that provides type-safe data transfer between the destinations.
  • Navigation Component also supports ViewModel. Can scope a view model to navigation graph to share UI related between destinations.

Getting Started with the Navigation Component

Note: Navigation Component requires Android Studio version 3.3 or above

Step 1: Create an empty activity project

Create an empty Activity Android Studio Project. And select Kotlin as the programming language. Android | How to Create/Start a New Project in Android Studio?.

Step 2: Adding the required dependencies

Following are the dependencies, need to be invoked inside the app-level Gradle file.

// nav_version may vary

def nav_version = “2.3.5”

// Navigation Component

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”

Add the following plugin inside the app-level Gradle file:

id “androidx.navigation.safeargs.kotlin”

Following is the classpath which is needed to be invoked inside the dependencies of the project-level or top-level Gradle file.

// nav_version may vary

def nav_version = “2.3.5”

classpath “androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version”

Step 3: Creating the first property of the Navigation Component

Creating the Navigation component Graph, which contains all the destinations. To create a Navigation Graph XML file “right-click on the res folder  -> Goto New -> and select Android Resource File”. This step is demonstrated in the below image.

Now give the name for the home fragment as navigation_graphs and select the Resource Type as Navigation and click on the OK button. This step is demonstrated in the below image.

Now create a new fragment by clicking on the + icon shown in the editor and select “Create New Destination” then blank fragment and click next. Now give the fragment name as fragment_1. This step is demonstrated in the below video

Now by following the previous step creates another fragment named fragment_2. Now add the Navigate button to fragment_1.xml file, as when it is clicked navigates to fragment_2. To implement the UI invoke the following code inside the fragment_1.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment_1"
    tools:ignore="HardcodedText">
  
    <TextView
        style="@style/TextAppearance.MaterialComponents.Headline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@id/navigate_button"
        android:layout_centerHorizontal="true"
        android:text="This is Fragment 1" />
  
    <Button
        android:id="@+id/navigate_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="NAVIGATE TO FRAGMENT 2" />
  
</RelativeLayout>


Now to differentiate between also make the UI changes inside the fragment_2.xml file. To implement the changes invoke the following inside fragment_2.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment_2"
    tools:ignore="HardcodedText">
  
    <TextView
        style="@style/TextAppearance.MaterialComponents.Headline6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="This is Fragment 2" />
  
</RelativeLayout>


Step 4: Adding actions to navigate from fragment 1 to fragment 2

From the navigation_graphs.xml under the design section drag and drop the arrow from fragment 1 to fragment 2. And then popUpTo fragment 1, as when the user clicks on the back button the user needs to be navigated to fragment 1. Refer to the following video if unable to get this step.

popUpTo pops the fragments to specified fragments from the backstack if the user presses the back button.

Step 5: Handle the button click from fragment 1

Handle the button click from fragment 1 to navigate to fragment 2. To implement the same invoke the following code inside fragment_1.kt file.

Kotlin




import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.navigation.fragment.findNavController
  
class fragment_1 : Fragment() {
  
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        val view: View = inflater.inflate(R.layout.fragment_1, container, false)
  
        // create instance of navigate button
        val navigateButton: Button = view.findViewById(R.id.navigate_button)
  
        // handle the navigate button to navigate to the fragment 2
        navigateButton.setOnClickListener {
  
            // if fragment_1Directions is giving error then rebuild the project
            val action = fragment_1Directions.actionFragment1ToFragment22()
            findNavController().navigate(action)
        }
  
        return view
    }
}


Step 6: Working with activity_main.xml

Now the in activity_main.xml, there is a need to host the start fragment, that is fragment 1. To implement the same invoke the following code inside the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="HardcodedText">
  
    <fragment
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_graphs" />
  
</androidx.constraintlayout.widget.ConstraintLayout>


Output:

The output looks odd and adding animations makes it look sleek. Follow the video given below to add animations to fragment transitions.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads