Android Up Navigation Won't Work on Toolbar using Navigation Component

Android Up Navigation Won't Work on Toolbar using Navigation Component

While recently learning the Navigation component in Android,  I was trying to make the navigation work with the Toolbar, however the Up navigation doesn't work.

I was following this official documentation and I made sure to follow all the steps. Below is a snippet of my code in MainActivity after following the documentation. All the navigation components work as expected but not the up navigation.

My app uses a single activity and all the destinations are Fragments. Here is the behavior on a fragment which is not one of the top level fragments specified in the AppBarConfiguration.

Up navigation doesn't work

I was at a loss trying to understand what I was missing. After some searching and trying multiple solutions I was finally able to get it working by adding the below line of code.

mainToolBar.setNavigationOnClickListener { _ ->  NavigationUI.navigateUp(navController, appBarConfiguration) }

The above code does the following:

setNavigationOnClickListener: This listener will be called whenever the user clicks the navigation button at the start of the toolbar. In our case the back arrow icon.

NavigationUI.navigateUp: Handles the Up button by delegating its behavior to the given NavController. This is an alternative to using NavController.navigateUp() directly when the given AppBarConfiguration needs to be considered when determining what should happen when the Up button is pressed

Ideally we do not have to perform the above step but if you have a single activity and are navigating to different fragment destinations, with few of the fragment destinations at the top level, this approach might be of help if you are also having the same issue.

Have a great day!