Hamid Hamid - 5 months ago 6
Android Question

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:


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.


@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) {
        return -1;

It would be used like this:

getResId("icon", Drawable.class);

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