Picture from Vlad Chețan on Pexels

Navigation Component, Bottom Navigation, and how to make them behave

I have been programming on Android for a while, and the only part of Jetpack I could never fit in any project was the Navigation component. Implementing it in an existing architecture looked like a lot of work that could be postponed (shame on me!), and I’ve never had a project that it quite fit into.

The scenario

The first step is to create the menu file that will host the entries for the bottom navigation:

Now, we can link the entries to the BottomNavigationView inside the Activity:

The last step is to create the empty Fragments we need to show: CurrentMealFragment and ProgressFragment. We don’t need them to have the UI, we just need them to be declared in the project.

Wiring the Navigation component

Now, we should add the NavHostFragment to the same Activity where the BottomNavigationView is, linking the Fragment to the navigation file we just created:

We can edit the mobile_navigation.xml file, and add our Fragments as destinations:

It’s important to note that the two Fragments must have the same IDs we declared in the menu file, otherwise, the Navigation Component would not find them.

Here we shared the code, but the same result could be achieved by using the Design tab on the mobile_navigation.xml file.

The last bit we need to wire up to make everything work is linking the NavController with the BottomNavigationView: to do so, we can invoke the setupWithNavController() extension function, passing in the NavController, that is retrieved by using yet another extension function:


If you want to check out the whole code, it’s available on GitHub.

A huge thank you goes to my friends Omar Miatello, that guided me through this journey, Corey Johnson, Daniele Bonaldo, and Fabio Collini for proofreading this post.

Android developer and GDE for Android