Read now

Jetpack Navigation in Android

Jetpack Navigation

In this blog, we are going to learn Jetpack Navigation, We will clarify what is Jetpack navigation, it’s benefits, and how to use it.

It simplifies implementing navigation, while also helping you visualize your app’s navigation flow. The library provides a number of benefits, including:

The Navigation component requires Android Studio 3.3 or higher and is dependent on Java 8 language features.
Overview

 

 

Overview

The Navigation Component consists of three key parts:

Integration

Just include the following code in the dependencies block of your module-level build.gradle file.

Navigation Graph

First, we will create a file that will contain our navigation graph. In the res, directory create a new android resource file as follows.

 

This will create an empty resource file named nav_graph.xml under the navigation directory.

We define these fragments in the navigation graph below.

Here the root tag named navigation has a parameter called startDestination which has the id of our first fragment. This defines that the first fragment will be loaded in the NavHostFragment automatically.

The Navigation Component introduces the concept of a destination. A destination is any place you can navigate to in your app, usually a fragment or an activity.

These are supported out of the box, but you can also make your own custom destination types if needed.

Notice that for first fragment we have defined an action with the following attributes:

Each action should have a unique id which we will use to navigate to the required destination.

Here the destination points to the id of the second fragment defined in the nav graph, which means that with this action we will navigate to the second fragment.

After this step when you open the nav_graph.xml and switch to the design tab, it should look like the following.

 

Navigation types

1. Navigation using destination Id

We can provide the id of the destination fragment to navigate to it, like the following

2. ClickListener

For views, we can also use createNavigateOnClickListener() method.

3. Navigation using Actions

As in the above nav graph, we have defined action in the first fragment, we can use the id of the action as follows

Define the NavHostFragment. It is a special widget it will display the different destinations defined in the nav graph. To load the FirstFragment then copy the following code and paste it in the layout of the activity.

Jetpack another library – Android Jetpack Compose

 

Thank you!

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close