0

How to change an image to the next one in the array using a for loop, once a button has been clicked. At present I have this in my on click method.

 int[] Pics = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};

 for (int i=0; i<Pics.length; i++){

     mainpic.setImageResource(Pics[i]);

 }

The problem is when the next button is clicked, it only stays at the first image or goes straight through to the last image.

Arslan Ali
  • 16,294
  • 7
  • 51
  • 65

3 Answers3

0

i quite dont get it ... you wrote that when you click the next button for next image its not working ... but what is not working ? this is for loop ... it will loop to the end of an array and set the image to the last image in it... what you need to define a class variable like

int[] Pics = {R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};
int i = 0;
mainpic.setImageResource(Pics[i]);

then inside next button onClick method ..

 i++;
 if(i >=3) {
   i = 0;
 }
 mainpic.setImageResource(Pics[i]);
Matej Špilár
  • 2,513
  • 3
  • 13
  • 27
  • this works perfect for looping through the images but give an out of bounds error when an intent is set at the if rather than i=0. Any ideas why? – user3535866 May 05 '14 at 15:47
0

try this block of code you are missing new int[]

int[] Pics = new int[]{R.drawable.pic1, R.drawable.pic2, R.drawable.pic3};

and use this inside of loop

int i = 0;

onClick method

mainpic.setImageResource(Pics[i]);
i++
Umer
  • 1,491
  • 2
  • 19
  • 29
  • thats not true ... you should read the ways how you can declare arrays in java ... http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java – Matej Špilár Apr 30 '14 at 10:19
  • ok you are right we have two ways of declaring arrays int[] myIntArray = {1,2,3}; int[] myIntArray = new int[]{1,2,3}; – Umer Apr 30 '14 at 10:25
0

You do not need for loop for this. Handle image change in onClick():

public void onClick(View view)
{
      if (view.getId() == R.id.<ButtonId>)
      {
           mainpic.setImageResource(Pics[currentImageIndex]);
           currentImageIndex = (currentImageIndex + 1) % Pics.Length;
      }
}

PS: currentImageIndex is a class variable. The % operation will allow you to change the image in a cyclic fashion.

Green goblin
  • 9,536
  • 13
  • 63
  • 97