Search code examples
androidmenuitem

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?


Solution

  • 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)