Navigation Component Starting Guide #1-Navigation Between Fragments

Enes Özdemir
Huawei Developers
Published in
3 min readDec 17, 2020

In the first article of Navigation Component Starting Guide we are going to talk about:

Navigation Component

How to navigate between fragments

How to add animations between transition

Navigation component consists of 3 important parts. Navigation graph (XML file), NavHost, NavController.

While navigating in the application, you can specify NavController the destination you want to go from a specific route in the Navigation graph or directly. Then NavController shows a suitable destination for you.

Navigation Component is for :

Managing the fragment transaction more efficiently

To manage events such as the Back button

Transferring data between views

How to implement it ?

First, we have to implement the libraries.

Now it’s time to create our navigation graph.

A navigation graph is a resource file that contains all of your destinations and actions. The graph represents all of your app’s navigation paths.

Let’s create nav_graph.xml.

Don’t forget to choose navigation as a Resource type.

Now it’s time to create and add our fragments to nav_graph.

Now that we created our nav_graph we need to add our action for navigation to the second fragment.

Lastly, we have to add Navigation Host to activity_main.xml.

Navigation Host is needed to perform fragment transactions.

It’s time to navigate between fragments through a button click.

Let’s open FragmentOne.

We need one NavController object to do the transitions.

To do this we need to override onViewCreated in FragmentOne.class.

After creating the NavController instance we can set Button click for navigation to the second fragment.

Navigating between fragments is successful.

Let’s add animations to transitions between fragments.

First, let’s create slide_in and slide_out animations.

We need to create an XML file that defines the type of animation to perform in a new folder anim under res directory (res->anim->slide_in.xml) with the required properties. Create anim directory first.

Then create slide_in_right.xml in anim folder.

And for smooth animation create slide_out_left.xml.

Our animation is ready now we just have to add our animation in our transmission action.

Congratulations now the transition between our fragments has animations :)

References:

Android Navigation Guide

Android Animation Examples

--

--