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

AndroidDev picture AndroidDev · Jun 5, 2013 · Viewed 24.2k times · Source

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"
/>

Answer

SteJav picture SteJav · Sep 17, 2013

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