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
If your activity includes fragments, the system first calls onOptionsItemSelected() for the activity then for each fragment (in the order each fragment was added) until one returns true or all fragments have been called.
Android Studio provides a standard XML format for the type of menus to define menu items. We can simply define the menu and all its items in XML menu resource instead of building the menu in the code and also load menu resource as menu object in the activity or fragment used in our android application.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With