Anonymous User
Anonymous User

Reputation: 31

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.

Upvotes: 0

Views: 771

Answers (1)

Prexx
Prexx

Reputation: 2979

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);

Upvotes: 2

Related Questions