Two Methods for dynamically obtaining resources based on the ID in Android
During development, we are used to implementing reference resources in a similar way:
context.getResources().getDrawable(R.drawable.flower);
However, what should we do if we know the resource id in advance and want to dynamically reference it, instead of fixing it in the id? For example, if the id of an image resource is R. drawable. test_1 and test_2 and test_3 are ordered, how can we dynamically reference them? There are two solutions: Directly Using Reflection and using the getIdentifier () method of resource. Their principles are similar to using reflection.
Method 1:
/*** Enter the id and 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 ;}
Method 2 (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;}
Res. three parameters in getIdentifier (): the first is the resource id name, the second is the class name, if the string type is String, there are also common drawable, layout, and so on, the third parameter is the project package name.
The above two methods can dynamically obtain resources. When we know that the IDs of some resources are regular, such as the same prefix, And the suffixes are sorted by a-z or number, you can dynamically construct IDs to obtain resources without having to write context every time. getResources (). getDrawable (R. drawable. test_1 );
I hope to help you.