JetPack Navigation Components in Android

After nearly a decade, the Android team introduces a new navigation system for developers

Photo by Chris Lawton on Unsplash
  1. Overview
  2. Integration
  3. Terminology
  4. Navigation Graph
  5. Navigation Types
  6. Safe Arguments
  7. Navigation With Arguments
  8. DeepLink with Navigation Component
  9. Enhancements for Navigation controller in Google I/O 2019
  10. Useful Links
  11. GitHub Sample

Overview

Navigation component is the one-stop solution to all the problems for any type of navigation in the android app. The JetPack Navigation component is a suite of libraries, tooling, and guidance that provides a robust navigation framework for in-app navigation

The navigation component provides a new type of navigation in android development, where we have a navigation graph to see all the screens and the navigation between them. It’s pretty much like storyboards in IOS.

The navigation component helps you to manage navigations, fragment transactions, backstack, animations, most importantly deeplinking (there is no need for intent filters with deeplinking any longer) and many more.


Integration

Include the following piece of code in your build.gradle and you’re good to go:

dependencies {
def nav_version = "2.1.0"

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

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

}

navigation-fragment: Fragment is a common architectural component that every developer uses, so navigation-fragment is an out the box library to use for fragment navigations.

navigation-ui: This is useful to help you set up the appbar, toolbar, and other material design components configuration with Nav Controller.


Terminology

NavHostFragment

NavController

Destinations

Actions


Navigation Graph

How to create a navigation graph

Creation of navigation graph

Steps to creating a navigation graph:

  1. In the Project window, right-click on the res directory and select New > Android Resource File. The New Resource File dialog appears.
  2. Type a name in the File name field, such as “nav_graph”.
  3. Select Navigation from the Resource type drop-down list, and then click OK.
navigation graph in project panel

Let me show you the navigation graph preview with a sample app of two fragments.

navigation graph preview

As every XML resource file nav_graph also has design and text tab, now let’s see the XML code in text tab to create a graph like above

Here the root tag will be navigation with startDestination attribute in which we have to mention the id of the fragment to be loaded initially. This is followed by destinations, like fragments, dialogs and so on, with one of the attributes name, whose value will be the name of your destination.

Now we come to the navigation. We use a tag action under a specific destination — where we want to initiate the navigation. There’s also an attribute in which we mention the destination ID.

Let’s put all the pieces together:

<?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_graph"
app:startDestination="@id/nav_fragment_one">

<fragment
android:id="@+id/nav_fragment_one"
android:name="com.m.navigationsample1.FragmentOne"
android:label="Nav Fragment One"
tools:layout="@layout/fragment_one">
<action
android:id="@+id/one_to_two"
app:destination="@id/nav_fragment_two"
app:enterAnim="@anim/nav_default_enter_anim"
app:exitAnim="@anim/nav_default_exit_anim"
app:popEnterAnim="@anim/nav_default_pop_enter_anim"
app:popExitAnim="@anim/nav_default_pop_exit_anim"
/>
</fragment>

<fragment
android:id="@+id/nav_fragment_two"
android:name="com.m.navigationsample1.FragmentTwo"
android:label="Nav Fragment Two"
tools:layout="@layout/fragment_two"/>

</navigation>

Navigation Types

With the navigation component we have multiple ways to navigate.

Navigation using ID

viewTransactionsButton.setOnClickListener { view ->
view.findNavController().navigate(R.id.viewTransactionsAction)
}

Click listener

button.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.next_fragment, null))

Navigate using Actions

findNavController().navigate(R.id.one_to_two)

Safe Arguments

Integration

ext.nav_version = '1.0.0'
classpath "android.arch.navigation:navigation-safe-args-gradle-plugin:$nav_version"

Now import the plugin into the module level Gradle file:

apply plugin: 'androidx.navigation.safeargs'

That’s it — the safe args plugin is active in your project.

Safe args helps you to safely pass the arguments. The main advantage of using safe args is that some of the checks that happen at runtime will now be done at compile time.

What safe args does is that it generates the code for the destinations with arguments which has functions. These functions have parameters based on the arguments you mentioned for the destination in the nav_graph.


Navigation With Arguments

Step 1

safe args in nav_graph

Here we mentioned two arguments: type string and an integer for fragment two. As I already said, safe args generate code for the destinations with name same as source class name appended with directions keyword. For example, here it generates FragmentOneDirections.

Pass arguments from source

Here we use FragmentOneDirections class to pass the arguments. Take a look:

btn_fragment_two_argument?.setOnClickListener {
val direction = FragmentOneDirections.oneToTwo()
direction.name = "Samule"
direction.id = 113
Navigation.findNavController(btn_fragment_two_argument).navigate(direction)
}

As I mentioned, nullable attribute to true — none of the arguments is mandatory. If you mention nullable as false then you should pass the non-null values in the constructor. You need to mention the default value for nullable arguments or your app may crash at runtime.

Receive the arguments in the destination

val args : FragmentTwoArgs? = arguments?.let{
FragmentTwoArgs.fromBundle(it)
}
args?.let {
var text_to_show = tv_fragment_two.text
text_to_show = "$text_to_show \nname : ${it.name} \nid : ${it.id}"
tv_fragment_two?.text = text_to_show
}

If you observed carefully, we got the name as string and ID as an int. That’s because of the type we mentioned in the nav_graph for those arguments.


DeepLink with Navigation Component

First, let’s see how we mention deeplink to a destination in nav_graph:

<fragment
android:id="@+id/nav_fragment_two"
android:name="com.m.navigationsample1.FragmentTwo"
android:label="Nav Fragment Two"
tools:layout="@layout/fragment_two">
<argument android:name="name"
app:argType="string"
app:nullable="true"
android:defaultValue="Default"/>
<argument android:name="id"
app:argType="integer"
android:defaultValue="-1"/>
<deepLink app:uri="http://mysitesampleapp.com/{name}/{id}"/>
</fragment>

You also need to implement the following line in your manifest file under the activity tag:

<activity android:name=".MainActivity">
<nav-graph android:value="@navigation/nav_graph" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

That’s it — deeplink is implemented in your app!

With the navigation component, we can invoke the fragment or activity through deeplink within the app:

btn_fragment_two_depplink?.setOnClickListener {
val name :String = "sam"
val id : Int = 123
val deeplink_uri = "http://mysitesampleapp.com/$name/$id".toUri()
Navigation.findNavController(btn_fragment_two_argument).navigate(deeplink_uri)
}

Enhancements for Navigation controller in Google I/O 2019

Useful Links

Introduction of Navigation Component

GitHub Sample

If possible I’m going to write the second part of this article, covering the advanced features of the navigation component.

Thank you for reading.

Better Programming

Advice for programmers.

Siva Ganesh Kantamani

Written by

Learn. Code. Write. Repeat. Visit me at https://about.me/sivaganesh_kantamani & Join my email list at https://tinyletter.com/Siva_Ganesh_Kantamani

Better Programming

Advice for programmers.

More From Medium

More from Better Programming

More from Better Programming

More from Better Programming

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade