An activity populates the ActionBar in its onCreateOptionsMenu()
method.
Instead of using setcustomview()
, just override onCreateOptionsMenu
like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
If an actions in the ActionBar is selected, the onOptionsItemSelected()
method is called. It receives the selected action as parameter. Based on this information you code can decide what to do for example:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
break;
case R.id.menuitem2:
Toast.makeText(this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
break;
}
return true;
}