Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Create a simple menu programmatically

Tags:

android

menu

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

like image 380
Shmuel Avatar asked Mar 03 '13 22:03

Shmuel


People also ask

What is onOptionsItemSelected() in Android?

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.

How to load menu through XML?

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.


1 Answers

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.

like image 85
Paul Avatar answered Oct 15 '22 23:10

Paul