Android Create a simple menu programmatically

2019-03-11 14:25发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

Programmatically, I was able to create a simple menu using the following code.

private final int MenuItem_EditId = 1, MenuItem_DeleteId = 0;

@Override
  public boolean onCreateOptionsMenu(Menu menu){

    MenuItem edit_item = menu.add(0, MenuItem_EditId, 0, R.string.edit);
    edit_item.setIcon(R.drawable.edit);
    edit_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    MenuItem delete_item = menu.add(0, MenuItem_DeleteId, 1, R.string.edit);
    delete_item.setIcon(R.drawable.delete);
    delete_item.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM);

    return super.onCreateOptionsMenu(menu);
}


回答4:

Here i implemented popup menu dynamically by using a click listener.

    Dynamic_PopUpMenu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PopupMenu menu = new PopupMenu(DialogCheckBox.this, v);
            menu.getMenu().add("AGIL");  // menus items
            menu.getMenu().add("Dash");  // menus items
            menu.getMenu().add("AGILarasan");
            menu.getMenu().add("Arasan");
            menu.show();
        }
    });


标签: android menu