Variable dynamically select Resource ID

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.