Support Navigation Button with Action Bar

 To add support for the up button, we first need to make sure our Activity has an ActionBar. We’ve already done this piece of the work for you, but to review:

1. Link the NavController to the ActionBar with NavigationUI.setupWithNavController.

Let's move to MainActivity. We need to find the NavController. Since we’re in the Activity now, we’ll use the alternate method of finding the controller from the ID of our NavHostFragment using the KTX extension function.

val navController = this.findNavController(R.id.myNavHostFragment)

Link the NavController to our ActionBar.

NavigationUI.setupActionBarWithNavController(this, navController)

2. Override the onSupportNavigateUp method from the activity and call navigateUp in nav controller.

Finally, we need to have the Activity handle the navigateUp action from our Activity. To do this we override onSupportNavigateUp, find the nav controller, and then we call navigateUp().

override fun onSupportNavigateUp(): Boolean {
   val navController = this.findNavController(R.id.myNavHostFragment)
   return navController.navigateUp()
}


Comments