1. Getidentifier method using the Resources class
Resources res=getresources ();
Return Res.getidentifier (Type, "drawable", Getpackagename ());
Here type represents the variable name, and Getpackagename () is replaced with the package name where your r resource file resides;
The Getresources method is derived from the CONTENXT (that is, the activity Class), which can directly return a Resouces object. The Getidentifier method of Resouces can return any resource ID in R.java, of course, you must specify 3 parameters: Field name, class name, package name. The package name specifies the fully qualified name of the package name section, if R is fully qualified named Android. R or COM.COMPANY.R, the package name here is "Android" or "Com.company". Getpackagename is actually this.getpackagename (), which returns the package name of this class directly.
The class name is the class to which the resource belongs. For example, we know that there are several fixed classes in the R.java class: Drawable, ID, string, layout, and so on, and many resource IDs are defined underneath them.
The field name is the name of the resource ID. For example, this resource ID definition: public static final int del=0x7f020002;
Del is the name of a resource ID, and 0x7f020002 is its 16 binary value.
With 3 parameters, the Getidentifier method can obtain a resource ID in a dynamic manner.
2, through reflection to obtain
try{ Field Field=r.drawable.class.getfield (type);//variable name int i= field.getint (new R.drawable ()) ; return i; }catch (Exception e) { log.e (tag,e.tostring ()); return r.drawable.unknow; }
Variable dynamically select Resource ID