Getting Started with the Navigation Component

October 12, 2021 Publish By : EXPERT APP DEVS 9 min read Viewed By : 947
started with navigation component

Introduction

Navigation component is an API or tool in Android that makes it much easier to create, manage and edit fragment transition flows and deep linking, and many more throughout the entire application. Before the Navigation component, navigation tasks in an application were handled manually. You can add a listener for whatever UI element you want to trigger or an open and for navigation action or launching an intent to show a new activity Or transition of a Fragment.

You also need to handle onbackpressed, when the user clicks on the device’s Back button. You need to handle events and open the last fragment when the user presses the back button in the application.

With the help of the Navigation component, we have standard APIs, also we can see visuals of the navigation graph in IDE, which helps us to make the entire process clearer, easier, and more consistent. you can design navigation graphs by using a designing tool. Then you need to add the code which connects user interaction in your app with different actions of your app.

Let’s see what it exactly looks like in the IDE and in the code. Let’s make an application.

Setup

Getting started with the Android Studio. You need to add navigation fragments and UI libraries to your project. They are available via the google() repository.

implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha01'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha01'

There is an optional step of including the safeargs navigation Gradle plugin. This plugin helps to generate code that allows type-safe access to properties used in argument capsules. You need to add the plugin to your project-level build.gradle classpath.

buildscript {
    ...
    repositories {
            google()
    }
    dependencies {
            ...
            classpath 'android.arch.navigation:navigation-safe-args-gradle-plugin:1.0.0-alpha01'
    }
}

In your project build.gradle, now you are able to add the Gradle plugin as you normally add.

apply plugin: 'androidx.navigation.safeargs'

The Navigation Graph

The navigation graph describes how fragments relate to each other and the ways in which you can transition between all fragments.

Here is an example of what exactly it looks like.

<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"
    app:startDestination="@+id/launcher_main">

    <fragment
        android:id="@+id/launcher_main"
        android:name="com.nishtahir.navigation.MainFragment"
        android:label="@string/home"
        tools:layout="@layout/fragment_main" />

    <activity
        android:id="@+id/dashboard_activity"
        android:name="com.nishtahir.navigation.SettingsActivity"
        android:label="activity_dashboard"
        tools:layout="@layout/activity_dashboard" />
</navigation>

Now we have the availability of destinations on the screen, we can use the Actions tag to navigate between fragments. Actions mean the intent to navigate between your destinations. We can add actions that navigate from the launcher_main fragment to the dashboard_activity.

<fragment
android:id="@+id/launcher_main"
android:name="com.nishtahir.navigation.MainFragment"
android:label="@string/home"
tools:layout="@layout/fragment_main">

<action 
android:id="@+id/action_launcher_main_to_dashboard_activity"
app:destination="@id/dashboard_activity" />

</fragment>

We can do this using the action tag along with providing a destination id where we intend to navigate.

We can apply transition animations for a transition like entering and Exit transition animations, as well as the Pop Enter and Pop Exit animations. You can apply or add default animations of the navigation library for transitions of the fragment under the nav_default prefix. such as nav_default_enter_anim. These are just simple fade animations.

Navigating

Now we have a basic navigation graph setup, we can start incorporating it into our code. We can do this by configuring an activity as a Host activity. This activity contains a NavHost widget which is an empty view that allows destinations to be attached in and out as per the user navigation command. Host activity can expect fragments and screens from the global navigation like Bottom Navigation Bar or Navigation Drawer.

The example of implementing the Navhost is as per below.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_nav_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:menu="@menu/bottom_navigation" />

    <fragment
        android:id="@+id/my_nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toTopOf="@id/bottom_nav_view"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/navigation" />

</android.support.constraint.ConstraintLayout>

In your host activity, you can use setupWithNavController which is available in the default NavigationUI class for setup. For example, let’s build a navigation graph to use a BottomNavigationView.

val navHostFragment = supportFragmentManager.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment
findViewById<BottomNavigationView>(R.id.bottom_nav_view)?.let { bottomNavView ->
    NavigationUI.setupWithNavController(bottomNavView, navHostFragment.navController)
}

The bottom navigation menu is displayed by an XML menu file this lists out the items of our menus and our destinations as well.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@id/launcher_main"
android:icon="@drawable/ic_home_white_24dp"
android:title="@string/home" />
<item
android:id="@id/launcher_dashboard"
android:icon="@drawable/ic_dashboard_white_24dp"
android:title="@string/dashboard" />
<item
android:id="@id/launcher_notification"
android:icon="@drawable/ic_notifications_white_24dp"
android:title="@string/notification" />
</menu>

Deep linking

Deep linking is a way for you to jump the user to a specific screen of your entire app. Following the basics of the Navigation graph, we also need to manage the back stack of the fragment and activity which was created and opened manually.

By adding the following to our XML file.


<nav-graph android:value="@navigation/navigation" />

Intent filters, as well as other setup and wiring business logic, will be created for us.

Finally, we can add URL in or deep-link inside the fragment, we only need to add path data to our fragment in our navigation graph file inside the deep link tag.

<deepLink app:uri="xyz.com/home" />

We can check and validate this by using our given Merged Manifest.

<activity android:name="com.nishtahir.navigation.MainActivity" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="http" />
        <data android:scheme="https" />
        <data android:host="xyz.com" />
        <data android:path="/home" />
    </intent-filter>
</activity>

Conclusion

Applying or using Navigation components in a project will help in the transition of screens and in the passing of data between the fragments. Navigation components automatically manage some of the crucial parts like deep linking, back stack, etc.. otherwise, become hard to work on with the fragment transition management system. With the help of NavHost, smooth fragments transitions can be handled inside the application. It reduces the complexity of creating fragment transition management and takes less time to build an application.

If you have any queries contact Android App Development Company now!

Need a consultation?

Drop us a line! We are here to answer your questions 24/7.