使用导航组件动态设置工具栏标题 [英] Set toolbar title dynamically using navigation-component
问题描述
我正在尝试动态设置工具栏标题,不知道是否可行.
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.
我尝试过:
it.findNavController().navigate(direction)
it.findNavController().currentDestination!!.label = someTitle
但这是行不通的.
有一些相关主题,即:
但这不能有效地解决我的问题,这是一种解决方法.
But it doesn't solve my problem efficiently, It's a work-around.
推荐答案
导航从
目标标签与NavigationUI方法一起使用时,现在将自动将 Destination labels, when used with NavigationUI methods, will now automatically replace 因此,您可以将标签设置为 Therefore you can set your label to 然后在构建路线时输入动态标题: Then pass in your dynamic title when constructing your directions: 当然,您可以自己收听导航事件并使用您自己的 Of course, you can listen for navigation events yourself and use your own 这篇关于使用导航组件动态设置工具栏标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!android:label
中的{argName}
实例替换为正确的参数
{argName}
instances in your android:label
with the correct argument b/80267266android:label="{dynamicTitle}"
,然后将参数传递给navigate
调用.在使用安全Args时,您想在目标位置添加一个参数: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>
val directions = YourDirections.actionToMyFragment(someTitle)
it.findNavController().navigate(directions)
OnDestinationChangedListener
可以执行所需的任何操作,包括将标签设置为所需的任何内容.不需要使用NavigationUI,并且在调用NavigationUI方法后添加的任何侦听器都将覆盖其设置.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.