public class BaseActivity extends AppCompatActivity implements
Toolbar.OnMenuItemClickListener {
private LinearLayout mContentLayout;
private Toolbar mToolbar;
//首先重写布局,改变层级,并重写setContentView方法,将新建的布局放进mContentLayout 中;
private void initContentView() {
ViewGroup content = (ViewGroup) findViewById(android.R.id.content);
content.removeAllViews();
mContentLayout = newLinearLayout(this);
mContentLayout.setOrientation(LinearLayout.VERTICAL);
content.addView(view);
view.addView(mContentLayout);
}
@Override
public void setContentView(int layoutResID) {
LayoutInflater.from(this).inflate(layoutResID, mContentLayout, true);
}
//这是主要方法,需要在setContentView方法前调用。这里传入之前做好的Toolbar布局id,如果有menu则传入
protected void setToolbar(int resId) {
setToolbar(resId, DEFAULT);
}
protected void setToolbar(int resId, int menuId) {
LayoutInflater.from(this).inflate(resId, mContentLayout, true);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
if(menuId != DEFAULT) {
mToolbar.inflateMenu(menuId);
}
setSupportActionBar(mToolbar);
mToolbar.setOnMenuItemClickListener(this);
}
@Override
public booleanonMenuItemClick(MenuItem item) {
return false;
}
}