Reputation: 48871
I'm in the process of converting an app I originally wrote to target v2.2 so it targets v4 using the v4 compatibility library and ActionBarSherlock.
I'm playing around with the ActionBar
Options menu and sub-menus and trying to work out how to identify sub-menu items in a unique fashion.
Example...
@Override
public boolean onCreateOptionsMenu(Menu menu) {
SubMenu mediaSubMenu = menu.addSubMenu("Media");
mediaSubMenu.add("Videos");
mediaSubMenu.add("Music");
}
That's fine and I get an ActionBar
menu item for "Media" and when I click I see the "Videos" and "Music" sub-menu items. My problem is the only way I've worked out to identify the sub-menu item which was clicked is as follows...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getTitle().equals("Music")) {
// Do something
return true;
}
return false;
}
It occurs to me though that I might have another sub-menu item with the same name, for example, "Settings" -> "Music".
How do I differentiate between the two? I can't help feeling I'm missing something very simple here.
Upvotes: 3
Views: 152
Reputation: 30652
Set ids for your MenuItems
mediaSubMenu.add(Menu.NONE, R.id.media_videos, Menu.NONE, "Videos")
you can define the id in a resource file (like res/values/ids.xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="media_videos" type="id"/>
<item name="other_videos" type="id"/>
</resources>
and you can then use
switch(item.getItemId()) {
case R.id.media_videos:
...
case R.id.other_videos:
...
}
I'd also recommend using the menu xml to set up your action bar data.
Upvotes: 3