如何从片段获取工具栏? [英] How to get Toolbar from fragment?
问题描述
我有ActionBarActivity与NavigationDrawer和使用support_v7工具栏的动作条。在我的片段一个工具都有自定义视图。在其他片段工具栏应该显示的标题。
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.
如何获得从碎片定制工具栏的实例?我可以用的ActionBar getActivity()。getActionBar(),但如果我叫的setTitle()此实例的ActionBar它什么都不做。
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
这篇关于如何从片段获取工具栏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!