javaandroidresourcesandroid-resources

Android, getting resource ID from string?


I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achieve this?

For example:

R.drawable.icon

I need to get the integer ID of this, but I also need access to the string "icon".

It would be preferable if all I had to pass to the method is the "icon" string.


Solution

  • @EboMike: I didn't know that Resources.getIdentifier() existed.

    In my projects I used the following code to do that:

    public static int getResId(String resName, Class<?> c) {
    
        try {
            Field idField = c.getDeclaredField(resName);
            return idField.getInt(idField);
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        } 
    }
    

    It would be used like this for getting the value of R.drawable.icon resource integer value

    int resID = getResId("icon", R.drawable.class); // or other resource class
    

    I just found a blog post saying that Resources.getIdentifier() is slower than using reflection like I did. Check it out.

    WARNING: This solution will fail in the release build if code/resource shrinking is enabled as suggested by Google: https://developer.android.com/build/shrink-code
    Also, it might fail for some other cases, e.g. when you have <string name="string.name">…</string> the actual field name will be string_name and not the string.name