Get started with the Navigation componen ...

Get started with the Navigation component — Beginner

Apr 21, 2022
185

image

This article shows you how to set up and work with the Navigation component

Android Jetpack, introduced at Google I/O 2018, was launched to build better applications using best practices and recommended architecture. Jetpack has brought several components and Navigation is one of them. And it’s never too late to learn and adapt to something new.

Navigation refers to the interactions that allow users to navigate across, into, and back out from the different pieces of content within your app. We usually do navigation with activities and fragments.

However, Google recommends the Single Activity Architecture moving forward when using Jetpack.

Firstly why fragments over activities?

Fragments are reusable components, build inside an activity, with their own layout interface and lifecycle. Passing data between fragments has been an easier task than activities. Fragments are also used for multi-pane UI such as Viewpager and bottom navigation.

Why navigation components?

Navigation Architecture gets rid of the complex FragmentTransaction by providing its own set of classes to navigate between fragments.

Providing all in one functionality with simple and fewer lines of code:

  • Handles fragment transactions automatically.

  • Default back press handling actions.

  • Type safety when passing information while navigating.

  • Effortless handling of navigation flow for visualizing and editing the fragments.

  • Effortless implementation for animations and Deep linking.

3 Key Concepts:

The Navigation component consists of three key parts that are described below:

  • Navigation graph

  • NavHost

  • NavController

Let’s Start… :)

1- Add dependencies

Open the build.gradle file in the app folder and add the following to the dependencies block:

implementation ‘androidx.navigation:navigation-fragment-ktx:2.4.1’ 
implementation ‘androidx.navigation:navigation-ui-ktx:2.4.1’

Then click on the sync now button to update the project.

2- Create your fragments

Make as many fragments as you want :) , In this sample , I have created 3 fragments.

3- Create a navigation graph

To add a navigation graph to your project, do the following:

  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” or “nav_main” or everything you want :)

  3. Select Navigation from the Resource type drop-down list, and then click OK.

4-Setup your fragment on Navigation Editor

After adding a graph, Android Studio opens the graph in the Navigation Editor. In the Navigation Editor, you can visually edit navigation graphs or directly edit the underlying XML.

image

  1. Destinations panel: Lists your navigation host and all destinations currently in the Graph Editor.

  2. 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.

  3. Attributes: Shows attributes for the currently-selected item in the navigation graph.

5-Add destinations to the navigation graph

You can create a destination from an existing fragment or activity. You can also use the Navigation Editor to create a new destination or create a placeholder to later replace with a fragment or activity.

In this example, let’s create a new destination. To add a new destination using the Navigation Editor, do the following:

  1. In the Navigation Editor, click the New Destination icon

image

, and then click Create new destination.

2. In the New Android Component dialog that appears, create your fragment. For more information on fragments, see the fragment documentation.

Back in the Navigation Editor, notice that Android Studio has added this destination to the graph.

6-Designate a screen as the start destination

The start destination is the first screen users see when opening your app, and it’s the last screen users see when exiting your app. The Navigation editor uses a house icon

image

to indicate the start destination.

Once you have all of your destinations in place, you can choose a start destination by doing the following:

  1. In the Design tab, click on the destination to highlight it.

  2. Click the Assign start destination button

image

. Alternatively, you can right-click on the destination and click Set as Start Destination.

7-Connect destinations

An action is a logical connection between destinations. Actions are represented in the navigation graph as arrows. Actions usually connect one destination to another, though you can also create global actions that take you to a specific destination from anywhere in your app.

With actions, you’re representing the different paths that users can take through your app. Note that to actually navigate to destinations, you still need to write the code to perform the navigation. This is covered in the Navigate to a destination section later in this topic.

You can use the Navigation Editor to connect two destinations by doing the following:

  1. In the Design tab, hover over the right side of the destination that you want users to navigate from. A circle appears over the right side of the destination

image

2.Click and drag your cursor over the destination you want users to navigate to, and release. The resulting line between the two destinations represents an action.

image

8-Add a NavHost to an activity

One of the core parts of the Navigation component is the navigation host. The navigation host is an empty container where destinations are swapped in and out as a user navigates through your app.

A navigation host must derive from NavHost. The Navigation component's default NavHost implementation, NavHostFragment, handles swapping fragment destinations.

Note: The Navigation component is designed for apps that have one main activity with multiple fragment destinations. The main activity is associated with a navigation graph and contains a NavHostFragment that is responsible for swapping destinations as needed. In an app with multiple activity destinations, each activity has its own navigation graph.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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">
<androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragmentContainerView"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_graph" />
</androidx.constraintlayout.widget.ConstraintLayout>

if you want to use your connection between your fragments ,just need call your action like :

binding.btnGoTo2.setOnClickListener
 { 
findNavController().navigate(R.id.action_firstFragment_to_secondFragment) 
}

it’s Done :)

Github Source :

https://github.com/Ezatpanah/Navigation-Component-Youtube

Also, you can check my video about this tutorial on YouTube :

https://www.youtube.com/watch?v=eS4bsQNqx_c

¿Te gusta esta publicación?

Comprar Reyhaneh (AndroidGeek.co) un café

Más de Reyhaneh (AndroidGeek.co)