Navigation component – Add library and make action

In this chapter of the Navigation component tutorial we are going to talk about how we can start using the Jetpack Navigation component in our exapmle project. First we are going to add the library to the build.gradle, then we will create the navigation graph and finally we are going to add the action to the buttons of the fragments.

GitHub

If you haven’t downloaded the starter project yet, then you can do it by clicking on the link below.

GitHub – Starter projcet

Step 1 – Adding Dependencies

To start working with the Navigation component, we have to add the dependencies to our project.

To do this, first open the starter project in Android Studio from GitHub. Then at the left side of the IDE will be a tab, called “Project”. Open it and expand the “Gradle Scripts”. Here open the Project build.gradle file.
The version

First, we are going to implement the version separetly. It means that we can follow the versions in one place. For this copy and paste this line inside of the buildscript part of the Project build.gradle file. 


nav_version 

When writting this tutorial, the version was 2.3.0-alpha03. You can find the currently highest version on the official Android developer website.

Android Navigation

The dependencies

Next, open the Module build.gradle file, what you can find next the Project build.gradle. Here, at the top you can find some lines, which start whit the keyword of “apply”. We are going to add a new line there.

apply plugin: ‘androidx.navigation.safeargs.kotlin’

Thenafter we are going to add the dependencies to our project. We will stay in the Module build.gradle file. Paste these twos line into the dependencies section.


The dependencies

Next, open again the Project build.gradle file. Here you will see, that this file has also a dependencies section. Paste there this line.

classpath “androidx.navigation:navigation-safe-args-gradle-plugin:$navigationVersion”

If you are done, then click in the top right part of Android Studio on the sync now label. Then the IDE will add the new dependencies for the project.

When the syncing has been finished, then you can close the build.gradle files.

Step 2 – Add the navigation graph

The Navigation component uses a navigation graph to manage the navigation of our app. A navigation graph is a resource file that contains all of our app’s destinations along with the logical connections, or actions, that the users can take to navigate from one destination to another. We can manage the navigation of our app’s navigation graph using the Navigation Editor in Android Studio.

Our app will contain only a top-level navigation graph. It means, that it should start with the initial destination. The user will see this when launching the app. It should include the destinations, what we can when we are browsing in the app.

Add new layout directory

The navigation graph will be located in the res folder. Here we are going to create a new directory, called “navigation”. So click with the right mouse button on the res folder, then select “New”, and finally click on the “Directory” option. 


In the popup window enter the name of “navigation” and click on the OK button.

Add the navigation graph

The next step is to create the navigation graph inside of the newly created directory. So click on it again with the right mouse button, then select “New”, and click on the “Navigation ressource” file option.

In the popup window name the new file as “navigation_graph”. The rest can stay the default selected. So click on the OK button.

Add the views to the graph

Still our graph is empty and the text in the center tells us to add some destionation using the “New Destination” button. You can find this button at the top left corner of the window. Click on it.

If you click on the button, then in the drop down menu you can see all of the fragments and the main activity. We are going to use all of them inside of this navigation graph. So what we have to do now, is just to click on the destinations and add all of them to the graph.

The navigation graph works like a canvas. You can drag the destinations and drop them eveywhere inside of the graph. After the addition, the destinations are overlapping each other. Drag them and position them as you can see on the picture below.


What you can see now is the design view of the graph. If you click on the middle button from the top right corner of Android Studio, then you will see the xml code as well.

The <navigation> element is the root element of the navigation graph. It has an important attribute, called startDestination. As we talked about earlier, this destination will be visible first, when the user opens the app.

Inside of the <navigation> element are the tags of the <fragment> and <acitivity>. These fields indicate whether the destination is implemented as a fragment, activity, or other custom class in the source code.

Currently all of these fields have the same attributes.

      • The id field contains the ID of the destinaiton which is used to refer to the destination in code.
      • The name field provides the linked class for the fragment or activity.
      • The label field will be the name of the destination in the navigation graph.
      • The value of the layout field shows which xml file belongs to the provided class.

As you can see in the xml view, we have an error, a red underline of the <navigation> element. It is there, because we haven’t provided the host fragment. We will correct it in the next step.

Step 3 – Add a NavHost to the main 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 our app.

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

Add a new xml file

We are going to implement the host fragment together with the AppBarLayout. Because of this, we are going to create them a new xml file and later on, we gonna include it inside of the activity_main.xml file.

So click witht the right mouse button on the layout folder, which is located inside of the res folder. Thenafter select “New”, and the “Layout ressource file” option. The name of the file will be “app_bar_with_fragment”.

Because later on we are going to implement the Navigation drawer for the app as well, we will include the app bar in this chapter.

Copy and paste the source code into the newly created xml file. 


app_bar_with_fragment.xml
Note
      • AppBarLayout is a vertical LinearLayout which implements many of the features of material designs app bar concept, namely scrolling gestures.
      • A Toolbar is a generalization of action bars for use within application layouts.
The styles

After the insertion, we will have two errors. These errors tell us, that still we haven’t implemented these styles in our app. So open the styles.xml file, which is located inside of the “res” -> “values” folders.

Then paste there these two lines:


AndroidManifest.xml

If you run now the app, then you will see that our app has 2 app bars. Because of the navigation drawer, we need to include in our app the AppBarLayout. So, to remove the original app bar, we have to create a new style in the style.xml file.

Open it and paste there this code.


Style of no title
In summary this style will tell for the app, that it doesn’t need the ActionBar and the title. But still our app doesn’t use this style.

So open from the “manifest” folder the AndroidManifest.xml file.

Inside of the <application> element will be an attribute, called theme.

android:theme=“@style/AppTheme”

Now, extend this line with our new style, then the default appbar won’t be there anymore.

android:theme=“@style/AppTheme.NoActionBar”

Step 4 – The actions

Currently we can implement actions between the frist 3 fragments. Because we are going to add the Navigation drawer to our app later, we can navigate from the Fragment_1 to the Fragment_2, then to the Fragment_3 using the buttons.

Create new actions
To create new actoins, open the navigation_graph.xml file. Here select the Fragment_1. Due to the selection, a blue circle will be visible in the center of the right edge. If you click on it, then you can connect Fragment_1 to Fragment_2. After that the arrow will represent the direction of the navigation. The name of this arrow is action.

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.

Now look at the xml code. In the part of the Fragment_1 will be a new element, called <action>. It has also a unique id and a destination attribute. The destination specifies which fragment will be opened, when we click on the button.

Also add an action to the Fragment_2. The destination should be Fragment_3.

After the 2 actions, the xml code of the navigation_graph.xml in case of the first 2 fragments looks like this.


AndroidManifest.xml

Before we will go forward, we have to rebuild the project. If we don’t do it, then the needed methods of the directions won’t be available and we can’t navigate to the next fragment.

Handle the clicks

The last step before we can run the app is to add the click listeners for the buttons.

Click listener for Fragment_1

So open from the fragment package the Fragment_1::class. Then press control+o and start typeing “onCreateView”. If you could find it, then double click on it. This will generate for us this method.

Inside of this method add the click listener for the button of btn_fragment_1.


setOnClickListener 

In the first step, we enabled the Safe Args. This plugin generates code that contains classes and methods for each actions we’ve defined. For each action, Safe Args also generates a class for each originating destination, which is the destination from which the action originates. The generated class name is a combination of the originating destination class name and the word “Directions”.

In our case the destination is named Fragment_1, the genereted class is named Fragment_1Directions. The generated class contains a static method for each action defined in the originating destination. This method takes any defined action parameters as arguments and returns a NavDirections object that we can pass to the navigate() method.

So inside of the click listnere paste this code.


navigate to Fragment_2
      1. Find a NavController given a Fragment
      2. Get the action
      3. Navigate to Fragment_2
Click listener for Fragment_2

Next is to add the same click listener to Fragment_2, inside of the onViewCreated() method.


navigate to Fragment_3

Run the app

If you run now the app, then you can use finally the fabolous Navigation Component. When you click on the btn_fragment_1, then the Fragment_2 opens. Then the Fragment_3 will be visible after clicking the btn_fragment_2 button.

GitHub

The source code is available on GitHub.

GitHub – add_library_and_make_action branch

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *