Android Create a simple menu programmatically

后端 未结 5 944
遥遥无期
遥遥无期 2021-02-01 12:36

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

5条回答
  •  梦谈多话
    2021-02-01 12:56

    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.

提交回复
热议问题