Set toolbar title dynamically using navigation-com

2020-04-06 07:18发布

问题:

I'm trying to set the toolbar title dynamically, I don't know if it's possible or not.

Assume I have list of items every item I clicked it's open new fragment, thus I trying to change toolbar title for each item dynamically.

I tried :

it.findNavController().navigate(direction)
it.findNavController().currentDestination!!.label = someTitle

But it doesn't work.

There are some related topics i.e:

How to set title in app bar with Navigation Architecture Component

But it doesn't solve my problem efficiently, It's a work-around.

回答1:

Navigation supports arguments in labels as of Navigation 1.0.0-alpha08 or higher:

Destination labels, when used with NavigationUI methods, will now automatically replace {argName} instances in your android:label with the correct argument b/80267266

Therefore you can set your label to android:label="{dynamicTitle}", then pass in an argument to your navigate call. As you're using Safe Args, you'd want to add an argument to your destination:

<fragment
    android:id="@+id/myFragment"
    android:name=".MyFragment"
    android:label="{dynamicTitle}">
  <argument
      android:name="dynamicTitle"
      app:argType="string"/>
</fragment>

Then pass in your dynamic title when constructing your directions:

val directions = YourDirections.actionToMyFragment(someTitle)
it.findNavController().navigate(directions)

Of course, you can listen for navigation events yourself and use your own OnDestinationChangedListener to do whatever you want, including setting the label to whatever you want. There's no requirement to use NavigationUI and any listener to add after calling the NavigationUI methods will override whatever it sets.



回答2:

Add addOnDestinationChangedListener to your navController and change the title, like this:

navController.addOnDestinationChangedListener(NavController.OnDestinationChangedListener { controller, destination, arguments ->
            when(destination.id)
            {
                R.id.itemHome->{
                    toolbar.title = "Radha Bangles"
                }
                R.id.itemCategories->{
                    toolbar.title = "Categories"
                }
                R.id.itemWishList->{
                    toolbar.title = "Wish List"
                }
                R.id.itemMyAccount->{
                    toolbar.title = "My Profile"
                }
                R.id.itemSettings->{
                    toolbar.title = "Settings"
                }
            }
        })