问题描述
我正在尝试创建一个viewpager,它可以通过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?
推荐答案
片段没有这样的方法setSupportActionBar()
. ActionBar是Activity的属性,因此要将工具栏设置为actionBar,您的活动应从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);
这篇关于将工具栏与片段一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!