Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 514
AndroidDev Avatar asked Jun 05 '13 11:06

AndroidDev


2 Answers

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

like image 142
SteJav Avatar answered Oct 11 '22 18:10

SteJav


Try this:

public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {

            case R.id.menu_printer_settings:
                    //do what you want  
                    break;
                }
}
like image 44
Jarvis Avatar answered Oct 11 '22 18:10

Jarvis