12

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?

AndyAndroid
  • 4,039
  • 14
  • 44
  • 71
  • You can see this question for an answer http://stackoverflow.com/questions/1714297/android-view-setidint-id-programmatically-how-to-avoid-id-conflicts – Ramseys Dec 05 '11 at 14:32
  • The first answer in that post says it can be duplicate, but what I am not understanding is how I can evaluate onOptionsItemSelected if the IDs are duplicates? The second response pointing to the example doesn't seem to fit. Maybe the example code has changed. – AndyAndroid Dec 05 '11 at 14:50
  • ID duplicate is very unlikely... Anyway, if you absolutely want to handle this situation, you can define a different `menuItemClickListener`with `setOnMenuItemClickListener(menuItemClickListener)` – Ramseys Dec 05 '11 at 15:08

2 Answers2

5

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)

Kevin Coulombe
  • 1,517
  • 1
  • 17
  • 35
  • 3
    If I use this overload (or NONE) how do you evaluate the onOptionsItemSelected method? You need to check there for the ID, otherwise you don't know what menu is pressed? – AndyAndroid Dec 05 '11 at 14:44
  • 1
    I usually simply add a different listener per menu item the functional way. But that's a personal preference. The add method returns a reference to the item it created. You could compare against that. – Kevin Coulombe Dec 05 '11 at 16:43
0

Silly solution for me was to create an xml resource layout menu with all my required buttons in there with id's then I'm able to refer to them in code using their own unique ID even though I'm not using that resource at all - literally just a register for randomly generated ID's effectively..

Mullazman
  • 507
  • 5
  • 15