I need to pass a resource ID to a method in one of my classes. It needs to use both the id that the reference points to and also it needs the string. How should I best achie
A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
In your res/layout/my_image_layout.xml
<LinearLayout ...>
<ImageView
android:id="@+id/row_0_col_7"
...>
</ImageView>
</LinearLayout>
To grab that ImageView by its @+id value, inside your java code do this:
String row = "0";
String column= "7";
String tileID = "row_" + (row) + "_col_" + (column);
ImageView image = (ImageView) activity.findViewById(activity.getResources()
.getIdentifier(tileID, "id", activity.getPackageName()));
/*Bottom code changes that ImageView to a different image. "blank" (R.mipmap.blank) is the name of an image I have in my drawable folder. */
image.setImageResource(R.mipmap.blank);
You can use this function to get resource ID.
public static int getResourceId(String pVariableName, String pResourcename, String pPackageName)
{
try {
return getResources().getIdentifier(pVariableName, pResourcename, pPackageName);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
So if you want to get for drawable call function like this
getResourceId("myIcon", "drawable", getPackageName());
and for string you can call it like this
getResourceId("myAppName", "string", getPackageName());
Read this
You can use Resources.getIdentifier()
, although you need to use the format for your string as you use it in your XML files, i.e. package:drawable/icon
.
The Kotlin approach
inline fun <reified T: Class<R.drawable>> T.getId(resourceName: String): Int {
return try {
val idField = getDeclaredField (resourceName)
idField.getInt(idField)
} catch (e:Exception) {
e.printStackTrace()
-1
}
}
Usage:
val resId = R.drawable::class.java.getId("icon")
For getting Drawable id from String resource name I am using this code:
private int getResId(String resName) {
int defId = -1;
try {
Field f = R.drawable.class.getDeclaredField(resName);
Field def = R.drawable.class.getDeclaredField("transparent_flag");
defId = def.getInt(null);
return f.getInt(null);
} catch (NoSuchFieldException | IllegalAccessException e) {
return defId;
}
}