Search code examples
androidandroid-jetpackandroid-architecture-components

How to change label attribute of a destination in navigation controller?


I am trying to use navigation controller in Android

enter image description here

as you can see in the image above, I set the label attribute of my destination to be 'Home'.

and this label, will show like title in my toolbar. can I change that label programatically ? because I want to set my toolbar title dynamically.

I have tried to change the toolbar title using toolbar.title = "some title here" but it will always be overlapped the title from that label.

so how to solve this ?


Solution

  • Do it in your activity like below it's worked for me:

     setSupportActionBar(toolbar)
        val navController = findNavController(R.id.nav_controller_fragment)
        val appBarConfiguration = AppBarConfiguration(navController.graph)
        setupActionBarWithNavController(navController, appBarConfiguration)
    
    
        navController.addOnDestinationChangedListener { controller, destination, arguments ->
            when (destination.id) {
                R.id.mainFragment -> toolbar.title = "ok"
                else -> {
                    toolbar.title = "General"
                }
            }
        }
    

    or if you want to change from your fragment do like below:

     override fun onStart() {
        super.onStart()
        (activity as MainActivity).toolbar.title = "changed"
    }