使用导航组件动态设置工具栏标题 [英] Set toolbar title dynamically using navigation-component

查看:214
本文介绍了使用导航组件动态设置工具栏标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态设置工具栏标题,不知道是否可行.

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方法一起使用时,现在将自动将android:label中的{argName}实例替换为正确的参数

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

因此,您可以将标签设置为android:label="{dynamicTitle}",然后将参数传递给navigate调用.在使用安全Args时,您想在目标位置添加一个参数:

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)

当然,您可以自己收听导航事件并使用您自己的OnDestinationChangedListener可以执行所需的任何操作,包括将标签设置为所需的任何内容.不需要使用NavigationUI,并且在调用NavigationUI方法后添加的任何侦听器都将覆盖其设置.

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.

这篇关于使用导航组件动态设置工具栏标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆