If I have different resource names like elephant, tiger and cat. And I want to create a method accepting the resource name and return the drawable object. Then I wrote this
public Drawable getDrawable(String name){
int defaultResId= ResourceOptimizer.getResId(name,R.drawable.class);
return getResources().getDrawable(defaultResId);
}
which the ResourceOptimizer
is
public class ResourceOptimizer {
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;
}
}
}
But the problem is that getResources()
needs to be called
in an activity or fragment, otherwise you to pass the context.
Passing the context might cause memory leak. Especially, when
it has to be passed through several classes. I’m wondering if
there is some way to get the resource by a better convenient way.
like
R.id.DRAWABLE_NAME