Search code examples
androidandroid-fragmentsandroid-architecture-navigationandroid-navigationandroid-bottomnav

How to change toolbar icon on fragment change from bottom navigation, using Navigation Component Lib?


I've setup my bottom navigation with navHostController, I've a container activity which has a toolbar, I want to change the icon in toolbar based on which fragment I'm on, this was easy if I didn't use navigation Component library.

MainActivity

 override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    bottomNavigationView.setupWithNavController(dashboardNavHostFragment.findNavController())
}

enter image description here

I want to change the icon in the toolbar to the fragment active in the bottom navigation.


Solution

  • You can use the addOnDestinationChangedListener.
    Something like:

    navController.addOnDestinationChangedListener { _, destination, _ ->
       if(destination.id == R.id.xxxx) {
           toolbar.setNavigationIcon(R.drawable.xxxx)
       } else {
           //
       }
    }