How To Get Resource Id Dynamically In Android

In Android, we normally use the R class in order to gain access to the drawable, layout, string (and others) variables.

I made this helper method to get a resource id dynamically. However, if you have no need for this, it is a better option to use the R class directly as the search operation is quicker compared to this.

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

Let us say, you have an XML file named help.xml in your res/layout/ folder. To use the method, do it like this.

getRestId("help", this, R.layout.class);

Donations appreciated. Every little $ helps. Or click Google +1. Or play the short video on the upper right of this page.

Related Posts Plugin for WordPress, Blogger...