Android Create a simple menu programmatically

A--C's method works, but you should avoid setting the click listeners manually. Especially when you have multiple menu items.

I prefer this way:

private static final int MENU_ITEM_ITEM1 = 1;
...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, MENU_ITEM_ITEM1, Menu.NONE, "Item name");
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_ITEM_ITEM1:
        clearArray();
        return true;

    default:
        return false;
  }
}

By using this approach you avoid creating unecessary objects (listeners) and I also find this code easier to read and understand.


Something like this might work:

public boolean onCreateOptionsMenu(Menu menu) {
  MenuItem item = menu.add ("Clear Array");
  item.setOnMenuItemClickListener (new OnMenuItemClickListener(){
    @Override
    public boolean onMenuItemClick (MenuItem item){
      clearArray();
      return true;
    }
  });
  return true;
}

Menu gives us a handy method, add(), which allows you to add a MenuItem. So we make one. Then we assign an OnMenuItemClickListener to the MenuItem and override its onMenuItemClick() to do what we want it to do.