Sometimes we want to dynamically based on a string resource name to obtain the corresponding resource ID, such as according to different image names to obtain the corresponding picture, at this time should consider how to implement.
As you know, when compiling Android project, the system will automatically generate a static resource class R, which has different static internal classes according to different resource types, such as id,drawable and so on, and each inner class holds the corresponding 16 binary static resource id attribute. The property name of these properties is the resource name. There are two common methods:
Method One:
Using Getresources (). Getidentifier (String name,string deftype,string defpackage) gets
Public int getresource (String imageName) { Context ctx=getbasecontext (); int resId = getresources (). Getidentifier (ImageName, "Mipmap", Ctx.getpackagename ()); // if imagename is not found under "mipmap", it will return 0 return resId;}
Method Two:
Use the reflection mechanism to get
Public intgetresource (String imageName) {Class mipmap= R.mipmap.class; Try{Field field=Mipmap.getfield (imageName); intResId =Field.getint (imageName); returnresId; } Catch(Nosuchfieldexception e) {//if imagename is not found under "mipmap", it will return 0 return0; } Catch(illegalaccessexception e) {return0; }}
PS: Gets the resource name according to the resource ID:
String resname = Getresources (). Getresourcename (ResId);
Android gets the corresponding resource ID based on the resource name of the string type