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?
int resourceID =
this.getResources().getIdentifier("resource name", "resource type as mentioned in R.java",this.getPackageName());
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @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<?> с) {
Field field = null;
int resId = 0;
try {
field = с.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
In Kotlin following works fine for me:
val id = resources.getIdentifier("your_resource_name", "drawable", context?.getPackageName())
If resource is place in mipmap folder, you can use parameter "mipmap" instead of "drawable".
I have found this class very helpful to handle with resources. It has some defined methods to deal with dimens, colors, drawables and strings, like this one:
public static String getString(Context context, String stringId) {
int sid = getStringId(context, stringId);
if (sid > 0) {
return context.getResources().getString(sid);
} else {
return "";
}
}