将工具栏添加到FragmentActivity [英] Adding toolbar to a FragmentActivity
问题描述
Am在一个类中扩展了FragmentActivity
,该类用作我的其他活动的基础活动.
我的问题是,当我从基本活动扩展其他活动时,我失去了工具栏功能.如何将其添加到我的基本活动中,以便我的活动可以继承工具栏?
有指针吗?
Am extending a FragmentActivity
in a class which serves as my base activity where my other activities extend from.
My issue is when I extend my other activities from my base activity, I loose toolbar functionality. How can I add this to my base activity so that my activities can inherit the toolbar?
Any pointers?
推荐答案
如果片段应具有ToolBar
的自定义视图,则可以为每个片段分别实现ToolBar
.
In case fragments should have custom view of ToolBar
you can implement ToolBar
for each fragment separately.
将ToolBar
添加到fragment_layout
中:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimaryDark"/>
在片段中找到它:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
//set toolbar appearance
toolbar.setBackground(R.color.material_blue_grey_800);
//for crate home button
ActionBarActivity activity = (ActionBarActivity) getActivity();
activity.setSupportActionBar(toolbar);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
菜单侦听器可以通过两种方式创建:
menu listener could be created two ways:
1.override onOptionsItemSelected
在您的片段中:
1.override onOptionsItemSelected
in your fragment:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
getActivity().onBackPressed();
}
return super.onOptionsItemSelected(item);
}
2.set在onCreateView
()中创建工具栏的侦听器:
2.set listener for toolbar when create it in onCreateView
():
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
return false;
}
});
这篇关于将工具栏添加到FragmentActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!