In development, we are used to implementing reference resources in a way similar to the following:
Context.getresources (). getdrawable (R.drawable.flower);
But what happens when we know the ID of this resource in advance and want to dynamically refer to it instead of curing it in the ID? For example, the ID of a picture resource is r.drawable.test_1, and there are test_2,test_3 in order, how do we dynamically refer to them? There are two scenarios: direct reflection and using the resource Getidentifier () method, They all have the same principle that they are implemented by reflection.
The first method:
/** * Enter ID, return BITMAP * @param context * @param ID * @return */public static Bitmap Getbitmapbyid (context context,string ID) {Bitmap Mbitmap=bitmapfactory.decoderesource (context.getresources (), Getresourceid ("Test_" +id); return mBitmap;} public static int Getresourceid (String name) { field field;try {field = R.drawable.class.getfield (name); return Integer.parseint (Field.get (null). ToString ());} catch (Nosuchfieldexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (NumberFormatException e) { TODO auto-generated catch Blocke.printstacktrace ();} catch (IllegalArgumentException e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch ( Illegalaccessexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return 0; }
The second method (more concise):
public static Bitmap Getbitmapbyid (Context context,string ID) {Resources res = context.getresources (); Bitmap Mbitmap=bitmapfactory.decoderesource (res, res.getidentifier (ID, "drawable", "com.test.android"), return Mbitmap;}
The second method Res.getidentifier () Three parameters: the first is the resource ID name, the second is the class name, if the string type is string, there are common drawable,layout and so on, the third parameter is the project package name.
The above 2 methods are able to dynamically acquire resources, when we know that some resources of the ID is regular, such as the same prefix, the suffix is a-Z or number sorting, etc., you can dynamically construct the ID to obtain resources, without having to write context.getresources () every time. getdrawable (r.drawable.test_1);
Hope to be of help to everyone.
Two ways to dynamically acquire resources based on ID names in Android