1、设置toolbar,直接在menu_main中添加item,并设置getSupportActionBar(toolbar),此时加载toolbar和实现点击事件如下:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main_toolbar, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
2、将toolbar设置为非actionbar形式
main_toolbar = (Toolbar) findViewById(R.id.main_toolbar);
//setSupportActionBar(main_toolbar);
main_toolbar.setTitle("MarkIt");
main_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
main_toolbar.setNavigationIcon(R.drawable.contact);
main_toolbar.inflateMenu(R.menu.menu_main_toolbar);
main_toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
int menuItemId = item.getItemId();
if(menuItemId==R.id.action_setting){
}
return false;
}
});
当调用inflateMenu加载布局时,需要实现点击监听,无需setSupportActionBar(),否则加载的是onCreateOptionsMenu()中的布局