必须在fragment初始化时
protected void initToolbar(View view) {
//fragment显示toolbar
setHasOptionsMenu(true);
if (mToolbar != null) {
((AppCompatActivity) mActivity).setSupportActionBar(mToolbar);
mToolbar.setTitle("");
}
}
创建菜单和菜单的点击事件
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (!hasToolbar()) {
return;
}
menu.clear();
if (menuResId != 0 || !TextUtils.isEmpty(menuStr)) {
inflater.inflate(R.menu.menu_toolbar, menu);
}
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
if (!hasToolbar() || mToolbar == null) {
return;
}
MenuItem menuItem = menu.findItem(R.id.menu_1);
if (menuResId != 0) {
menuItem.setIcon(menuResId);
}
if (!TextUtils.isEmpty(menuStr)) {
menuItem.setTitle(menuStr);
}
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == R.id.menu_1 && onClickListenerTopRight != null) {
onClickListenerTopRight.onClick();
return true;
}
return false;
}
});
super.onPrepareOptionsMenu(menu);
}