Android Jetpack Navigation Component | Jetpack 101

Android Jetpack Navigation Component | Jetpack 101

In this article, we’ll see what exactly is Navigation component and how to implement it.

Android Jetpack is a suite of libraries, tools, and guidance to help developers write high-quality apps easier.

What’s Navigation Component?

The Navigation Component makes it easier to navigate between fragments by handling fragment transactions, deep-links, transitions, animations and navigation UI components.

Navigation component is Google’s mindset to a single Activity approach, with one main activity and rest fragments.

Benefits:

  • Simplified setup for common navigation patterns

  • Handles backstack

  • Automates fragment transactions

  • Type safe argument passing

  • Handles transition animations

  • Simplified deep links

  • Centralizes and visualizes navigation

The navigation component consists of *three *key parts —

Navigation graph:

It’s an XML resource file that contains the host, graphs destinations and actions that connect them.

Navigation graph

Navigation graph

NavHost:

NavHost is an empty container that is used to display destinations from the navigation graph.

NavController:

The NavController is used to manage the navigation of the app within a NavHost.

When we navigate through the app using the NavController, the NavController shows the appropriate destination in the NavHost.

Let’s start implementing it!

Implementation :

First, we need to add the dependencies in the app-level build.gradle file —

def nav_version = "X.Y.Z"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"

replace the ***X.Y.Z ***with the latest stable version.

now, sync the project.

Then, we create a new resource directory of resource type navigation and name the directory **navigation. **We’ll see a new directory ‘navigation’ created inside res folder.

In the *navigation *directory, we’ll create a new ***navigation resource file. ***In this example I’ve named it navigation_graph but you can name it whatever you like.

Now if we open the file, we should see this —

Blank Navigation graph

Blank Navigation graph

Now, we’ll modify the activity_main.xml and replace the default <TextView/> with the <fragment/> given below —

<fragment
    android:id="@+id/fragment_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:navGraph="@navigation/navigation_graph"/>

Once we’ve done that, we should see a host destination added to the Navigation graph (in navigation_graph.xml)

Navigation graph with a host

Navigation graph with a host

Now we can add a new destination by clicking on the ‘Click to add a destination’ option in the center of the navigation graph. Then select ‘create new destination’ options, this will open Android New Component Dialog where we can create a new Fragment.

For this example, we’ll three fragments namely — MainFragment, FirstDestination and SecondDestination. After creating these Fragments, the navigation graph should look something like this —

Navigation graph with destinations

Navigation graph with destinations

The MainFragment layout will have two Buttons (with id’s as — goToFirstDestination and goToSecondDestination) and one EditText( with id — editText).

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import kotlinx.android.synthetic.main.fragment_main_fragment.*

class MainFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_main_fragment, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        goToFirstDestination.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.to_firstDestination))
        goToSecondDestination.setOnClickListener{
            val valueBundle =Bundle()
            valueBundle.putString("valueArgs",editText.text.toString())
            it.findNavController().navigate(R.id.secondDestination,valueBundle)

        }
    }
}

Here, the goToFirstDestination button will simply go to the FirstDestination fragment and the goToSecondDestination button will pass the value from the editText to the SecondDestination fragment.

Since we’re passing values from MainFragment to SecondDestination, we need to add an argument to the second by click on the + icon in **Argument **panel from the Attribute section.

Add argument dialog

Add argument dialog

That’s it! Now when you run the app.

You can also add Actions and Deep Links through the navigation graph.

In Android, a deep link is a link that takes you directly to a specific destination within an app. To add deep-link, click on the + icon in **Argument **panel from the **Deep Link **section. In the Add deep link dialog, enter the URI.

All the functionalities above are implemented in this repository.

Follow for more Jetpack series!

Did you find this article valuable?

Support Abhishek Kumar by becoming a sponsor. Any amount is appreciated!