如何从片段中获取工具栏? [英] How to get Toolbar from fragment?

查看:44
本文介绍了如何从片段中获取工具栏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 ActionBarActivityNavigationDrawer 并使用 support_v7 Toolbar 作为 ActionBar.在我的片段工具栏中有一个自定义视图.在其他片段中 Toolbar 应该显示标题.

I have ActionBarActivity with NavigationDrawer and use support_v7 Toolbar as ActionBar. In one of my fragments toolbar has custom view. In other fragments Toolbar should show title.

如何从片段中获取用于自定义的 Toolbar 实例?我可以使用 getActivity().getActionBar() 获取 ActionBar,但是如果我为此实例 ActionBar 调用 setTitle() 它什么都不做.

How get Toolbar instance for customizing from fragments? I can get ActionBar with getActivity().getActionBar(), but if I call setTitle() for this instance ActionBar it do nothing.

UPD:

就我而言

((ActionBarActivity) getActivity()).getSupportActionBar().setTitle();

(正如 MrEngineer13 所说)在第一个片段创建时不起作用,因为我从 onHiddenChanged() 调用它.现在我在 onCreateView() 中添加了更多,它工作正常.

(as MrEngineer13 said) don't work at first fragment creation because I call it from onHiddenChanged(). Now I add more one to onCreateView() and it works fine.

推荐答案

您需要先将您的活动从 getActivity() 转换为 AppCompatActivity.举个例子:

You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle();

你必须投射它的原因是因为 getActivity() 返回一个 FragmentActivity 而你需要一个 AppCompatActivity

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

在 Kotlin 中:

In Kotlin:

(activity as AppCompatActivity).supportActionBar?.title = "My Title"

这篇关于如何从片段中获取工具栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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