简体   繁体   中英

How to draw specific drawable resource programmatically?

I have a set of images in my drawable resources. Now I want to be able to change a placeholder image accordingly with image.setImageResource(R.id.name_of_image) programmatically.

My ImageView is defined as ImageView image = findViewById(R.id.placeholder);

How would I do this? I have tried getIdentifier but that didn't work.

The images have the format Name.jpg

EDIT:

I currently have the following construction:

int resID = getResources().getIdentifier(name.toLowerCase(), "drawable", this.getPackageName());
ImageView image = findViewById(R.id.placeholder);
image.setImageResource(resID);

I have changed the image name to lowercase and it is now a png file.

Your images has to be in png format (prefered by android) and must contain only lowercase letters and digits ([a-z0-9_.]. Then you can use

image.setImageResource(R.drawable.name_of_image);

You can get the name of the drawable with this:

String name = context.getResources().getResourceEntryName(R.drawable.name_of_image);

To get the drawable with the string name:

int id = context.getResources().getIdentifier("name_of_image", "drawable", context.getPackageName());
image.setImageResource(id);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM