Set toolbar title dynamically using navigation-component

只愿长相守 提交于 2020-03-16 05:41:30

问题


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"
                }
            }
        })


来源:https://stackoverflow.com/questions/55700759/set-toolbar-title-dynamically-using-navigation-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!