1

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.

Brian
  • 819
  • 4
  • 20
  • 35

2 Answers2

4

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

jsonfry
  • 2,067
  • 2
  • 15
  • 16
  • Thanks for the reply. I thought about doing that but I have about 50 images, not 5 (lost the zero somewhere). Would that method be a problem? Will it affect the performance? – Brian Jan 18 '11 at 21:00
  • Hmm, I can't imagine it making a particularly striking impact on performance, but it wouldn't make for very nice code. It might be worth popping it in it's own static class to keep 50 horrible lines away from your main code, but then I'm somewhat of clean code whore... – jsonfry Jan 18 '11 at 22:28
  • @Brian 50 images might be a lot to hold in memory. – Cheryl Simon Jan 18 '11 at 23:17
  • 1
    @Mayra you're not actually holding the images in memory, just an integer that refers to their id. – jsonfry Jan 18 '11 at 23:45
  • I have different categories of images, so at any given time, the array would at the most be 20 images (or integers). I have not noticed a slow down in performance on my device, but its not like its storing the full image like fry15 stated. Thanks for the help. – Brian Jan 19 '11 at 17:43
4

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.

Community
  • 1
  • 1
Cheryl Simon
  • 46,552
  • 15
  • 93
  • 82