Using Toolbar with Fragments(使用带有片段的工具栏)
问题描述
我正在尝试创建一个浏览器,它可以浏览 3 个不同的片段,每个片段都有不同的工具栏.我之前在一个活动中实现了新工具栏并让它工作但是我试图让它与片段一起工作
I am trying to create a viewpager that swipes through 3 different fragments each with a different toolbar. I have implemented the new toolbar in an activity before and got it to work however I am trying to get it to work with fragments
这是片段代码
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout resource that'll be returned
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_home);
if (mToolbar != null) {
setSupportActionBar(mToolbar);
}
mToolbar.setTitle(null);
return rootView;
}
我正在使用 Fragment 扩展我的片段,但是我收到了错误
I am extending my fragment with Fragment, however I am getting the error
Cannot resolve method setSupportActionBar
我不确定如何解决这个问题,如果我删除 setSupportActionBar 代码,它会停止在某些设备上工作吗?
I am not sure how to resolve this, if I remove the setSupportActionBar code will it stop working with certain devices?
推荐答案
Fragments 没有这样的方法 setSupportActionBar().ActionBar 是 Activity 的一个属性,所以要将你的工具栏设置为 actionBar,你的 Activity 应该从 ActionBarActivity 扩展,然后你可以在你的 Fragment 中调用:
Fragments don't have such method setSupportActionBar(). ActionBar is a property of Activity, so to set your toolbar as the actionBar, your activity should extend from ActionBarActivity and then you can call in your Fragment:
((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar);
更新
如果您使用的是 AppCompatActivity:
((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar);
这篇关于使用带有片段的工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用带有片段的工具栏
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
