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.
2 Answers 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);
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.