How do I get the resource id of an image if I know its name? [duplicate]
How do I get the resource id of an image if I know its name (in Android)?
Solution 1:
With something like this:
String mDrawableName = "myappicon";
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
Solution 2:
You can also try this:
try {
Class res = R.drawable.class;
Field field = res.getField("drawableName");
int drawableId = field.getInt(null);
}
catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
}
I have copied this source codes from below URL. Based on tests done in this page, it is 5 times faster than getIdentifier(). I also found it more handy and easy to use. Hope it helps you as well.
Link: Dynamically Retrieving Resources in Android
Solution 3:
Example for a public system resource:
// this will get id for android.R.drawable.ic_dialog_alert
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android");
Another way is to refer the documentation for android.R.drawable class.