Add the dependencies
The first thing to do is add the following dependencies :
-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.
Clicking Ok will create a new
res file and open the 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
TextRecognitionFragment for later use.
Back to the Navigation Editor, we now have a host in
Click the add destination button to add fragments as destinations to the editor.
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 the
nav_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
val navController = findNavController(R.id.mainNavFragment)
- we find the
- we setup the
toolbar, the toolbar’s title will be automatically updated when navigating
- we setup the
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.