Reputation: 819
I apologize if this seems really simple but I can't figure it out. I have an ImageButton that I want to change the image of at run-time based on a button click. I have 5 images in my res folder. When the user hits the "Next" button, I want it to go to the next image. The file names of the images are image1.png, image2.png, etc.
I know I you can change the image by doing:
imgButton.setImageResource(R.drawable.image2);
I have a counter (int) to keep track of the image number being displayed. But how would i change the image to the next image? Any help would be appreciated.
Upvotes: 1
Views: 6076
Reputation: 46844
You can use reflection to get the id of an image based on a string filename.
Field f = R.getClass().getField("image2");
int id = f.getInt(null); // use null for static fields
imgButton.setImageResource(id);
Edit:
Or as this other question mentioned, you can ask Resources for the id using getIdentifier()
. This is slower than getting by static const, but might work for you.
Upvotes: 4
Reputation: 2087
Create an Array of integers to hold the references to your images, e.g.
int[] images = new int[5];
images[0] = R.drawable.image001;
images[1] = R.drawable.image002;
images[2] = R.drawable.image003;
images[3] = R.drawable.image004;
images[4] = R.drawable.image005;
And then increment your counter on each click, and set the image resource using a value from your array:
imgButton.setImageResource(images[counter]);
Easy when you know how... ;)
Upvotes: 4