androidstringmenuresourcesmonkeyrunner

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

  • Solved it by getting all the fields for the package

            Map<Integer, String> idMap = new HashMap<Integer, String>();
            Class<?> r;
            String rClass = activity.getBaseContext().getApplicationContext().getPackageName()
                    + ".R$id";
            try {
                r = Class.forName(rClass);
            } catch (ClassNotFoundException e1) {
                Log.log("Unable to load " + rClass + ": " + e1.getMessage());
                return idMap;
            }
            for (Field f : r.getFields()) {
                int val;
                try {
                    val = f.getInt(null);
                } catch (Exception e) {
                    throw new IllegalStateException("Unable to get value for " + f.getName() + ": "
                            + e.getMessage());
                }
                idMap.put(val, f.getName());
    
            }