'How to get the Android ID for a menu item in Android?

Is there a way to get the Android ID for a menu item? I can see getTitle() but not a getId(). I'm interested in the ID value "menu_printer_settings" rather than the title value "printer_settings" and the menu item ID (getItemId()). I need this ID to make my Monkey Talk scripts work for localized builds also.

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/menu_printer_settings"        
    android:title="@string/printer_settings"
/>



Solution 1:[1]

Solution1:

MenuItem item

String[] id = getResources().getResourceName(item.getItemId()).split("\\/");

then access id[1]

Solution2:

Use titleCondensed to match the id e.g.

<menu>
            <item android:id="@+id/myid"
                  android:title="some menu title"
                  android:titleCondensed="myid"/>
...
</menu>

then

String selectedMenuIdString = (String) item.getTitleCondensed();

I prefer Solution 1 since I don't have to repeat the id name.

Hope this helps. Regards Steve

Solution 2:[2]

Try this:

public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {

            case R.id.menu_printer_settings:
                    //do what you want  
                    break;
                }
}

Solution 3:[3]

Try using getItemID() also have a look at the following if you are still having problems:

MenuItem.getItemId returns 0 instead of ItemId

Solution 4:[4]

Menu menu = null;
menu.findItem(R.id.item_id);

This way you access the menu item anyway in activity or fragment

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 SteJav
Solution 2 Jarvis
Solution 3 Community
Solution 4 David Buck