将工具栏设置为片段中的操作栏 [英] Set up toolbar as actionbar in fragment
问题描述
我想将工具栏设置为操作栏,但由于工具栏是一个布局,因此必须在您的布局中。现在我的布局在我的片段中。
I want to set up my toolbar as an actionbar, but since your toolbar is a layoutelement it has to be in your layout. Now my layout is in my fragment.
我在布局中添加了工具栏,我在我的片段中调用它:
I added the toolbar in my layout and I call it within my fragment:
//Toolbar
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
它有效,因为我可以设置标题等等但现在我希望它作为动作栏做出反应因为我想要这样做。 setDisplayHomeAsUpEnabled(true)
It works because I can set the title and so on but now I want it to react as a actionbar because I want to have this actually. setDisplayHomeAsUpEnabled(true)
要做到这一点,我必须将工具栏更改为操作栏:
To do that I have to change the toolbar to an actionbar:
setSupportActionBar(toolbar);
这在我的片段中不起作用...
That doesn't work in my fragment ...
任何人都可以帮助我让我的工具栏作为片段中的操作栏工作。
Can anybody help me to get my toolbar to work as an actionbar in a fragment.
推荐答案
现在<$不推荐使用c $ c> ActionBarActivity 所以
您需要将您的活动从 getActivity()
转换为 AppCompatActivity
首先。这是一个例子:
Now ActionBarActivity
is deprecated so
You need to cast your activity from getActivity()
to AppCompatActivity
first. Here's an example:
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle();
您必须投放它的原因是因为 getActivity()
返回 FragmentActivity
,你需要一个 AppCompatActivity
The reason you have to cast it is because getActivity()
returns a FragmentActivity
and you need an AppCompatActivity
这篇关于将工具栏设置为片段中的操作栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!