Add the Navigation Architecture Component to your App

The Navigation Architecture Component simplifies the implementation of navigation in an Android app.

In this story, I’m gonna explain how to add and start using Navigation Component.

I’ll start from the app I created for my previous article.

Add the dependencies

The first thing to do is add the following dependencies :

implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha05'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha05'

Note: the -ktx is because I’m using Kotlin. If you’re using Java, just remove it.

Create the navigation graph

Next, create a new resource file (right-click on the res folder, new -> Android Resource File) called nav_graph.xm and select “Navigation” as Resource type.

Create nav_graph.xml

Clicking Ok will create a new res file and open the Navigation Editor

Empty Navigation Editor

As you can see, the Navigation editor is empty. You need to create a NavHostFragment (Navigation Host Fragment).

Add NavHostFragment to yourActivity

Create a NavHostFragment and define where he finds the navigation graph.


Create other Fragments

I had to refactor my app by creating an ImageLabelingFragment and move everything previously in my MainActivity . I also created 2 new fragments BarcodeReaderFragment and TextRecognitionFragment for later use.

Setup destinations

Back to the Navigation Editor, we now have a host in activity_main called mainNavFragment .

Click the add destination button to add fragments as destinations to the editor.

Navigation editor with destinations

The destination with little home icon means it’s the starting destination in the graph. To change it, select a destination and click the Set Start Destination button.

At that point, this is what thenav_graph.xml looks like:


As you can see, the ids of my fragments are exactly the same as the bottom_nav.xml items ids.


This way, only two lines of code will be necessary to configure the BottomNavigationView with the navigation graph.

Setup the Activity

Now, in the MainActivity we add the following lines in the onCreate method:

val navController = findNavController(
  1. we find the NavHostFragment
  2. we setup the toolbar, the toolbar’s title will be automatically updated when navigating
  3. we setup the BottomNavigationView

Aaaaaand that’s it ! Navigation Component is now up and running for the app.

That’s also the end of that introducing story to Navigation Architecture Component. There’s a lot more to tell about it so I’ll continue to experiment with it and I’ll share my discoveries with you. The source code of the app can be found here.

Thanks for reading.