If you haven’t downloaded the starter project yet, then you can do it by clicking on the link below.
Step 1 – Adding Dependencies
To start working with the Navigation component, we have to add the dependencies to our project.
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.
When writting this tutorial, the version was 2.3.0-alpha03. You can find the currently highest version on the official Android developer website.
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.
Next, open again the Project build.gradle file. Here you will see, that this file has also a dependencies section. Paste there this line.
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.
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.
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”.
Copy and paste the source code into the newly created xml file.
- 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.
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:
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
So open from the “manifest” folder the AndroidManifest.xml file.
Inside of the <application> element will be an attribute, called theme.
Now, extend this line with our new style, then the default appbar won’t be there anymore.
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
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.
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.
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
- Find a NavController given a Fragment
- Get the action
- 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.
The source code is available on GitHub.
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂