Dynamically obtain the corresponding resource id based on a resource name, dynamically corresponding to the resource id

Source: Internet
Author: User

Dynamically obtain the corresponding resource id based on a resource name, dynamically corresponding to the resource id

In the process of project creation, a requirement is met. In the Android code, images can be dynamically loaded using the image ID. To load the image in the Android folder, we need to know its ID. to dynamically obtain the image ID, we need to dynamically obtain the image ID.

So what should we do?

Resources res=getResources();String packageName =getPackageName();imageView.setImageBitmap(BitmapFactory.decodeResource(res,res.getIdentifier(pracData.getQuestion(),"drawable",packageName)));

We can use

Res. getIdentifier (String str, "drawable", packageName) to obtain the image ID.
If stris the image name and the title is a.png, str is.
Drawable is the folder for storing images.
PackageName is the package name of the activity.

Next, let's talk about how to dynamically obtain other resource IDs.

 

1. Get the layout resource ID

Int layoutId = getResources (). getIdentifier ("activity_main", "layout", getPackageName ());

 

2. obtain image resources (in the mipmap file)

Int mipmapId = getResources (). getIdentifier ("ic_launcher", "mipmap", getPackageName ());

 

3. Get character Resources

Int stringId = getResources (). getIdentifier ("author", "string", getPackageName ());

Related Article

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.