Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting itemId in options menu

I have a menu defined via an XML resource. Now dynamically I add a menu item

public boolean onCreateOptionsMenu(Menu menu) 
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);

    if(myCondition==true)
    {
        menu.add(0, 99, 0, "new Entry");

    }

    return true;
}

In onOptionsItemSelected(MenuItem item) I have a case statement which checks for "99" and it performs my actions. Technically that works fine, I just wonder what number, here 99, I shall pick? The items created in the XML got an ID via the resource file, I assume Android has some logic to create these items. I wonder if it can happen that a generated menu item gets by accident as well 99 and then it won't work anymore. What would be the best way?

like image 527
AndyAndroid Avatar asked Dec 05 '11 14:12

AndyAndroid


People also ask

How to add menu option in android?

To define the menu, create an XML file inside your project's res/menu/ directory and build the menu with the following elements: <menu> Defines a Menu , which is a container for menu items.

What is option menu android?

In android, Options Menu is a primary collection of menu items for an activity and it is useful to implement actions that have a global impact on the app, such as Settings, Search, etc. Following is the pictorial representation of using Options Menu in our android applications.

How can I hide menu items in android?

If you want to change the visibility of your menu items on the go you just need to set a member variable in your activity to remember that you want to hide the menu and call invalidateOptionsMenu() and hide the items in your overridden onCreateOptionsMenu(...) method.


1 Answers

I always used the overload with just a title parameter, but looking at the docs, it seems you can pass NONE.

http://developer.android.com/reference/android/view/Menu.html#add(int, int, int, int)

like image 151
Kevin Coulombe Avatar answered Oct 14 '22 00:10

Kevin Coulombe