我做了一个通用的布局,在每个活动中包含V7工具栏,并使用它的公共类文件CommonToolbar.java
来处理它的属性。
layout_common_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_common"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/abc_action_bar_default_height_material"
android:background="?attr/colorPrimaryDark"/>
CommonToolbar.java
public class CommonToolbar {
Activity activity;
Toolbar toolbar;
CommonToolbar(Activity activity, View view, String title) {
super();
this.activity = activity;
toolbar = (Toolbar)view.findViewById(R.id.toolbar_common);
toolbar.setTitle(title);
toolbar.setTitleTextColor(activity.getResources().getColor(R.color.white));
}
void setNav() {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
activity.onBackPressed();
}
});
}
void setMenuListner() {
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
/* case R.id.searchItem:
Toast.makeText(getApplicationContext(), "Search", Toast.LENGTH_SHORT).show();
break;
case R.id.filterItem:
Toast.makeText(getApplicationContext(), "Filter", Toast.LENGTH_SHORT).show();
break;*/
}
return true;
}
});
toolbar.inflateMenu(R.menu.common_toolbar_menu);
}
}
使用它像:
布局
<include android:layout_height="@dimen/abc_action_bar_default_height_material"
android:id="@+id/includeSurgicalDetail"
android:layout_width="match_parent"
layout="@layout/layout_common_actionbar"/>
活动
View includedLayout = findViewById(R.id.includeSurgicalDetail);
CommonToolbar commonToolbar = new CommonToolbar(SurgicalDetail.this, includedLayout, pName);
commonToolbar.setMenuListner();
commonToolbar.setNav();
但是我收到以下错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.greyline.eswasthyaprojectv3/com.eswasthyaV3.SurgicalDetail}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.Toolbar.setTitle(java.lang.CharSequence)' on a null object reference
答案 0 :(得分:0)
如果您不想编写相同的选项菜单代码,则应extend
改为Activity
。
写一个BaseActivity
类,如:
public class BaseActivity extends Activity{
protected Toolbar toolbar;
public void onCreate(Bundle savedInstaceState){
super.onCreate(savedInstanceState);
//initialize the Toolbar, set the menu listener, nav, etc
toolbar = (Toolbar)findViewById(R.id.toolbar_common);
}
}
然后,对于您希望拥有共享代码的所有Activity
,请展开BaseActivity
而不是Activity
。因此,您不需要反复编写相同的选项菜单代码。