Android Create a simple menu programmatically

Shmuel picture Shmuel · Mar 3, 2013 · Viewed 52.2k times · Source

I'm trying to create a simple menu with one button that will call a method to clear the array. I don't want to use xml because all I need is one button.

Something like this -

public boolean onCreateOptionsMenu(Menu menu) {
    button "Clear Array";
    onClick{// run method that wipes array};
    return true;
}

Thank you

Answer

Paul picture Paul · Mar 3, 2013

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.