Android gets the corresponding resource ID based on the resource name of the string type

Source: Internet
Author: User

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

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.