1

I have 10 images on /resources/drawable folder as following names;
pr1.gif, pr2.gif, ... pr10.gif
And I can easily set an image like this;
imgview1.setImageResource(R.drawable.pr5);

But I can't set it like following;

int pr = getpr(dm);
imgview1.setImageResource(R.drawable.pr + pr);

Is there a way to set it like this or should I use switch case?

1
  • I would recommend switch statements. Commented Oct 11, 2013 at 13:38

1 Answer 1

1

You can get the id of a drawable by name using getIdentifier():

String prefix = "pr";
int suffix = getpr(dm); // I assume this returns the image number

Resources res = getResources();
int resId = res.getIdentifier(prefix + suffix, "drawable", "my.package.name");
imgview1.setImageResource(resId);

Note you can use this for any type of resource, whether it's drawable, string, array, etc. Just make sure you change the second parameter from "drawable" to the appropriate type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.