0

Consider I have two images image_name1.png, image_name2.png in drawable resources of android. Now I would like set image like below,

imageView.setImage(R.drawable.image_+"MyChoice"+.png);

where MyChoice can be name1 or name2 or some string

Is that possible, or do we have any solution to achieve that?

2
  • 1
    What exactly are you trying to do? Are you trying to change the image of an ImageView based on some condition? Commented Mar 8, 2016 at 4:19
  • Are you set two images in single imageView?? Commented Mar 8, 2016 at 4:20

4 Answers 4

5

you can do by uri

String uri = "@drawable/imname"; //imname without extension

int imageResource = getResources().getIdentifier(uri, null, getPackageName()); //get image  resource

Drawable res = getResources().getDrawable(imageResource); // convert into drawble

imageView.setImageDrawable(res); // set as image
Sign up to request clarification or add additional context in comments.

Comments

1

Resources.getIdentifier does what you're looking for.

int resId = context.getResources().getIdentifier("image_"+myChoice, "drawable", "com.myapp.mypackage");
if(resId == 0) {
    resId = R.drawable.default;
}
imageView.setImageResource(resId);

1 Comment

how can I use above snippet when drawable present in different versions like drawable-mdpi, drawable-hdpi but not present in drawable
0

You can't do that. What you can do is something like:

int images[] = {R.drawable.image1, R.drawable.image2};

imageView.setImage(images[mychoice]);

Or something similar with a hash table if you want to do strings instead of integer indexes.

As an aside- you don't put the .png in the drawable name in code. THe point of drawable is that you shouldn't need to know if its png, jpg, or even xml.

1 Comment

Hey @Gabe Sachan check the answer I upvoted, that's working for me
0

there are two posibilties

1.

int  MyChoice=1 or 2;
`imageView.setImage(R.drawable.image_+MyChoice+.png);`

second is

int image=Integer.parseInt("R.drawable.image_"+MyChoice+".png");
imageView.setImage(image);

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.