问题
In order to create a tile management system I have a pack of image in my res/drawable directory. How to load that ressource dynamically ?
like : F_16.0_0_112.jpg. ("F_"+zoom"+"._"+XCoord+"_"+YCoord".jpg")
Is there a fonction like getDrawable(String) ?
回答1:
You can get a drawable using its name by:
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
回答2:
You can get this using reflection (dont forget to import java.lang.reflect.Field)
/**
* For example calling <code>getDrawableId("ic_launcher")</code> will return the same value as <code>R.drawable.ic_launcher;</code>
*
* @param name the name of the field
* @return the drawable id
*/
public int getDrawableId(String name) {
Class<?> c = R.drawable.class;
Field f = null;
int id = 0;
try {
f = R.drawable.class.getField(name);
id = f.getInt(null);
} catch (NoSuchFieldException e) {
Log.i("Reflection", "Missing drawable " + name);
} catch (IllegalAccessException e) {
Log.i("Reflection", "Illegal access to field " + name);
}
return id;
}
回答3:
No, for this use android assets folder.
Please see more details here.
回答4:
Unfortunatly no, you can't load resources by name. The id's are variables in the generated R class. In java, you can't build dynamic variable names.
来源:https://stackoverflow.com/questions/13266774/how-to-get-list-of-image-with-r-drawable