I want to access a resource like a String or a Drawable by its name and not its int id.
Which method would I use for this?
in addition to @lonkly solution
method:
/**
* lookup a resource id by field name in static R.class
*
* @author - ceph3us
* @param variableName - name of drawable, e.g R.drawable.image
* @param с - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class> с)
throws android.content.res.Resources.NotFoundException {
try {
// lookup field in class
java.lang.reflect.Field field = с.getField(variableName);
// always set access when using reflections
// preventing IllegalAccessException
field.setAccessible(true);
// we can use here also Field.get() and do a cast
// receiver reference is null as it's static field
return field.getInt(null);
} catch (Exception e) {
// rethrow as not found ex
throw new Resources.NotFoundException(e.getMessage());
}
}