59

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

Shmuel
  • 3,916
  • 2
  • 27
  • 45

6 Answers6

86

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.

Paul
  • 5,163
  • 3
  • 35
  • 43
  • 1
    I like this also. Definitely gonna use this in the future – Shmuel Mar 03 '13 at 22:26
  • 1
    +1, but: On android 4? compiler error, because the break after return statement. I will try to edit it, done –  Apr 09 '13 at 08:03
  • 2
    > "A--C's method works, but you should avoid setting the click listeners manually. Especially when you have multiple menu items." But why? What's bad about adding a listener onto each menu item directly? (it seems more maintainable to me to have each item's info+reaction self-contained, not split into two places) – Venryx May 26 '20 at 12:13
  • 1
    Unless someone can justify why setting click listeners manually should be avoided, I agree with Venryx! – Ted Henry Nov 19 '20 at 00:48
32

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.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • @David no problem. Since you need only one button (like you specified in your question), this is fine, and takes up less code. But as Paul said, if you have multiple buttons, it is recommended that you follow that approach. – A--C Mar 03 '13 at 22:26
  • Recommended by whom? – Ted Henry Nov 19 '20 at 00:48
27

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);
}
Vikas
  • 4,263
  • 1
  • 34
  • 39
6

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();
        }
    });
Agilanbu
  • 2,747
  • 2
  • 28
  • 33
2

If you're looking for generated popup items with callbacks, used this.

Java

public static void popupMenu(final Context context, View anchor, final LinkedHashMap<String,IPopupMenu> options){
        PopupMenu popupMenu = new PopupMenu(context, anchor);
        for(String key : options.keySet()){
            popupMenu.getMenu().add(key);
        }
        popupMenu.getMenuInflater().inflate(R.menu.popup_menu,popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem menuItem) {

                options.get(menuItem.getTitle()).onClick();
                return true;
            }
        });

        popupMenu.show();
    }

public interface IPopupMenu{
        void onClick();
    }

XML

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

</menu>

Example

LinkedHashMap<String,IPopupMenu> menu_items = new LinkedHashMap<>();
menu_items.put("Item Name", new Utils.IPopupMenu() {
         @Override
         public void onClick() {
            //do your code
         }
});
menu_items.put("Clear Array", new Utils.IPopupMenu() {
         @Override
         public void onClick() {
            //clear array
         }
});

popupMenu(context,button,menu_items);
NJY404
  • 349
  • 3
  • 14
0

In Kotlin you can dynamically add a menu item like this:

class MyFragment : MyBasicFragment() {
    companion object {
        const val MENU_ITEM_ID_UPDATE = 0
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        // consider you have called 'inflater.inflate(R.menu.app_bar_menu, menu)' in the MyBasicFragment
        super.onCreateOptionsMenu(menu, inflater)

        menu.add(0, MENU_ITEM_ID_UPDATE, 0, R.string.menu_item_update).apply {
            setIcon(R.drawable.ic_baseline_refresh_24)
            setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM)
        }
    }
}
James Bond
  • 2,229
  • 1
  • 15
  • 26