Wednesday, 5 December 2012

String To Resource ID

Wow, this is one hell of a delayed post ! But nevertheless ... 

A lot of times, when we try to templatize / automate a product, we face the problem of converting a string to its corresponding resource id. For example, a simple input from the user for the drawable name that he/she would want to select for a button. This input will essentially be in the format of a string. Now to map this string to the corresponding drawable id is the task we propose the following solution -

public static int getResId(String variableName, Context context, Class<?> c) {

    try {
        Field idField = c.getDeclaredField(variableName);
        return idField.getInt(idField);
    } catch (Exception e) {
        return -1;

The usage will be -

getResId("icon", context, Drawable.class);

Thats all for now folks !