{{announcement.body}}
{{announcement.title}}

Android Jetpack Tutorial: How to Implement Android Navigation Component in Your App

DZone 's Guide to

Android Jetpack Tutorial: How to Implement Android Navigation Component in Your App

In this article, we discuss create a navigation component with Kotlin and Jetpack in an Android application.

· Web Dev Zone ·
Free Resource

From this Android navigation component tutorial, you will learn:

  • What is Android jetpack’s navigation component?
  • Benefits of the navigation component.
  • When to use navigation component.
  • How to implement Android navigation component in your application.

You must be hearing a lot about Android Jetpack, which is a set of components, tools, and guidance to make great Android apps.

When it comes to talking about Android components, they are highly useful for Android developers while developing an app.

Components, like Coroutine and Live Data, Data Binding, Paging, ViewModel, Security, Sharing, WorkManager for background jobs, and Navigation are the collection of libraries that are individually adaptable and built to work together. Among these components, WorkManager, Navigation, and Paging are new. Therefore, we are covering tutorials on these new components. Earlier, we covered WorkManager, and now here we are covering Navigation.

What Is Navigation?

Generally, navigation refers to the interactions, allowing users to navigate across, into, and back out from different pieces of content within your application.

The newly launched Android Jetpack’s Navigation component is launched as a framework for structuring your in-app UI, focusing on making a single activity app. From simple button clicks to complex patterns like app bars and the navigation drawer, this component helps to implement navigation.

Moreover, this component also ensures a consistent and predictable user experience by adhering to an established set of principles. It consists of three parts:

  • Navigation Graph: It is an XML resource, which has all the information related to navigation in one centralized location. It comprises all the individual content areas within your app known as destinations.
  • NavHost: An empty container, showing destinations from the navigation graph. This component contains a default NavHost implementation and NavHostFragement that shows fragment destinations.
  • NavController: A single object which manages app navigation within a NavHost.

Moving ahead, let’s discuss the benefits of Android Jetpack’s Navigation component.

You may also like: Android App Architecture: Modularization, Clean Architecture, MVVM.

Benefits of Android Navigation Component

  • It handles fragment transactions easily with its available API.
  • It allows users to check the flow of the application through a navigation graph.
  • It provides standardized resources for animations and transitions.
  • It implements and handles deep linking.
  • It handles up and back actions correctly by default.

To know about this component, you can refer to this Android development guide that was released by Google. In our Android app development tutorial, you will learn how to implement the Navigation component in your Android application.

Let’s Get Started

Step 1 

First of all, add the dependency in the application module Gradle file (build.gradle).

Groovy




xxxxxxxxxx
1


1
 dependencies { def nav_version = "2.1.0" 
2
// navigation implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" 
3
implementation "androidx.navigation:navigation-ui-ktx:$nav_version" }



Step 2

In the Project or Android Window, Right-click on the res directory and create a new Android Resource Directory with Resource Type as Navigation. Then, add a new Navigation Resource File and name it whatever you want; this way your navigation graph will be created.

Your navigation graph will contain three main sections:

  • Destinations panel: Lists your navigation host and all destinations currently in the Graph Editor.
  • Graph Editor: Contains a visual representation of your navigation graph. You can switch between Design view and the underlying XML representation in the Text view.
  • Attributes: Shows attributes for the currently-selected item in the navigation graph.

Click the Text tab to see the corresponding XML of the Navigation Graph

Step 3 

Now, take one fragment in your MainActivity in which you want to navigate to other fragments.

XML




xxxxxxxxxx
1


 
1
<fragment
2
   android:id="@+id/nav_host"
3
   android:name="androidx.navigation.fragment.NavHostFragment"
4
   android:layout_width="match_parent"
5
   app:defaultNavHost="true"
6
   app:navGraph="@navigation/nav_graph"
7
   android:layout_height="match_parent"
8
   />



Step 4

Now, create one other blank fragment to navigate from the Home Fragment to the newly created fragment.

Step 5  

Now, add both the fragments into the Navigation Graph.

You can add Action, Arguments, and Deep-links from Navigation itself, which will help to pass the data between the Fragment while Switching.

All the Actions will define the transition and destination (i.e. the route of the application through navigation). Arguments will define the default value to a particular key, and Deep-links will forward the user to a particular screen within the app.

Step 6 

Now, in the Home Fragment, add the following code to your corresponding view’s on click event to navigate to the next fragment.

Kotlin




x


 
1
 class HomeFragment : Fragment() {    
2
   override fun onCreateView(       
3
     inflater: LayoutInflater, 
4
     container: ViewGroup?,       
5
     savedInstanceState: Bundle?   
6
   ): View? {       
7
     val view = inflater.inflate(R.layout.fragment_home, container, false)    
8
     if (view != null) {           
9
       init(view)       
10
     }        
11
     
12
     return view   
13
   }    
14
   
15
   private fun init(view: View?) {       
16
     view?.findViewById(R.id.tvShowAll)?.setOnClickListener { 
17
       val bundle = bundleOf("userText" to "John Connor")
18
       
19
       Navigation.findNavController(view).navigate(
20
         R.id.action_homeActivity_to_allFragment)
21
     }
22
    
23
     view?.findViewById(R.id.tvShowBikes)?.setOnClickListener {           
24
       val bundle = bundleOf("userText" to "Jack Sparrow") 
25
     Navigation.findNavController(view).navigate(
26
         R.id.action_homeActivity_to_bikesFragment, bundle)       
27
     }
28
     
29
     view?.findViewById(R.id.tvShowCars)?.setOnClickListener {
30
       Navigation.findNavController(view).navigate(
31
         R.id.action_homeActivity_to_carsFragment)
32
     }
33
     
34
     view?.findViewById(R.tvShowTrucks)?.setOnClickListener {
35
       Navigation.findNacController(view).navigate(
36
         R.id.action.homeActivity_to_trucksFragment)
37
     }
38
   
39
   }
40
 }
17
       val bundle = bundleOf("userText" to "John Connor")


Step 7: After adding 3-4 fragments in your project and adding all of them into the navigation graph, your navigation graph’s design and the text (XML) file of your Navigation Graph will look something like this:

Java




x
72


 
1
<?xml version="1.0" encoding="utf-8"?>
2
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
3
   xmlns:app="http://schemas.android.com/apk/res-auto"
4
   xmlns:tools="http://schemas.android.com/tools"
5
   android:id="@+id/nav_graph"
6
   app:startDestination="@+id/homeFragment">
7
 
          
8
   <fragment
9
       android:id="@+id/homeFragment"
10
       android:name="com.spaceo.testconfirm.navigationgraphdemo.Views.HomeFragment"
11
       android:label="fragment_home"
12
       tools:layout="@layout/activity_home">
13
       <action
14
           android:id="@+id/action_homeActivity_to_carsFragment"
15
           app:destination="@id/carsFragment"
16
           app:popEnterAnim="@anim/nav_default_pop_enter_anim"
17
           app:popExitAnim="@anim/nav_default_pop_exit_anim"
18
           app:popUpTo="@id/carsFragment" />
19
       <action
20
           android:id="@+id/action_homeActivity_to_allFragment"
21
           app:destination="@id/allFragment"
22
           app:enterAnim="@anim/nav_default_enter_anim"
23
           app:exitAnim="@anim/nav_default_exit_anim"
24
           app:popUpTo="@id/allFragment" >
25
 <argument
26
               android:name="userText"
27
               app:argType="string"
28
               android:defaultValue="Hello World 2" />
29
       </action>
30
       <action
31
           android:id="@+id/action_homeActivity_to_bikesFragment"
32
           app:destination="@id/bikesFragment"
33
           app:popUpTo="@id/bikesFragment" />
34
       <action
35
           android:id="@+id/action_homeActivity_to_trucksFragment"
36
           app:destination="@id/trucksFragment"
37
           app:popUpTo="@id/trucksFragment" />
38
 
          
39
   </fragment>
40
 
41
   <fragment
42
       android:id="@+id/bikesFragment"
43
       android:name="com.spaceo.testconfirm.navigationgraphdemo.Views.BikesFragment"
44
       android:label="fragment_bikes"
45
       tools:layout="@layout/fragment_bikes" >
46
       <argument
47
           android:name="userText"
48
           app:argType="string"
49
           android:defaultValue="Hello World3" />
50
   </fragment>
51
   <fragment
52
       android:id="@+id/carsFragment"
53
       android:name="com.spaceo.testconfirm.navigationgraphdemo.Views.CarsFragment"
54
       android:label="fragment_cars"
55
       tools:layout="@layout/fragment_cars" >
56
       <argument
57
           android:name="userText"
58
           app:argType="string"
59
           android:defaultValue="Hello World1" />
60
   </fragment>
61
   <fragment
62
       android:id="@+id/trucksFragment"
63
       android:name="com.spaceo.testconfirm.navigationgraphdemo.Views.TrucksFragment"
64
       android:label="fragment_trucks"
65
       tools:layout="@layout/fragment_trucks" />
66
   <fragment
67
       android:id="@+id/allFragment"
68
       android:name="com.spaceo.testconfirm.navigationgraphdemo.Views.AllFragment"
69
       android:label="fragment_all"
70
       tools:layout="@layout/fragment_all">
71
   </fragment>
72
</navigation>



Output

Example output


Conclusion

From this tutorial, you learned how to implement Android jetpack’s navigation component in your Android application. However, you also checked the basic information about this component like what it is and the benefits of this component.

Following this step-by-step tutorial, you can implement the Android navigation component without any hassle. In fact, you can refer to this demo and download the source code from Github.


Further Reading

Topics:
android ,android jetpack ,tutorial android ,mobile apps ,mobile apps development ,mobile apps development agency

Published at DZone with permission of Pradeep Makhija . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}