Picture from Vlad Chețan on Pexels

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

Roberto Orgiu
2 min readJun 8, 2020

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

This time around, I wanted to get a first-hand experience with many of the technologies I never get to use in a new project, a small app that will guide me through my diet. The UI that I have in mind requires a BottomNavigationView that will be linked to two Fragments.

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

Once we have our View setup, we can link each Fragment to the related entry. As the first step, we should create an XML file in the navigation folder of the app’s resources: let’s call it mobile_navigation.xml.

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:

Conclusion

Once all these steps have been performed, no more code is needed to navigate using the BottomNavigationView, and the only changes needed if we want to change the entries would be in the menu file, and in mobile_navigation.xml.

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.

--

--