1

I have a bunch of images named, 1.jpg, 2.jpg... and 56.jpg. I also have an _id value in a variable dependent on which item was selected from the previous list activity. I have the following code to display an image.

ImageView image = (ImageView) findViewById(R.id.headerimage);
image.setImageResource(R.drawable.image1);

What I would like to do is dynamically display the image that corresponds with the _id value, e.g.. something like this?

ImageView image = (ImageView) findViewById(R.id.headerimage);
image.setImageResource(R.drawable.myID + ".jpg");

How do I do that?

Cheers,

Mike.

asked Dec 14, 2011 at 23:22

2 Answers 2

2

Yes, you can do this.

Just use Resouces.getIdentifier(). Be aware that this implementation is slower that using the id and always check if the resourceId is not 0 (that would mean the resource you asked for doesn't exit.

Example:

 View view = //...
 int number = //...   
 int resId = getIdentifier("files_"+number, "drawable", "com.my.project.package");
 view.setBackgroundResource(resId);
answered Dec 14, 2011 at 23:44
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Pedro, it worked perfectly! and Sander, your example would have worked two and I love the lateral thinking but I have 150 images. Cheers,
0

As far as I know, you don't. I had a similar problem a while ago, you can find it here. For some reason, Android doesn't seem to like it if you try to reference resource names dynamically. I eventually fixed it by putting all the resources that I dynamically wanted to reference in an Array.

answered Dec 14, 2011 at 23:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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