使用带有片段的工具栏
我正在尝试创建一个浏览器,它可以浏览 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);
相关文章