Dynamically change the image of an imageView (Android Studio)?

0

I have an imageview with two buttons, forward and backward. In a gallery of 5 photos I would like to be changing the image so that one button advances one image and the other one goes back. I know how to just jump to a specific image. Can anyone help?

    
asked by anonymous 09.04.2018 / 18:37

1 answer

1

Make a vector with the images:

int[] imagensIds = {
    R.drawable.image1,
    R.drawable.image2,
    R.drawable.image3
};

//E um int para saber qual posição

int i = 0;  

Your image loads the first with the position of "i":

img.setImageResource(imagensIds[i]);

And then clicking the button:

button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 i++;
                 img.setImageResource(imagensIds[i]);
             }
         });

If it were to go back you would use "i -"

But here it is up to you to do an if to check if it is already in the last image so it does not reach for example i = 3 and there is no index 3 in the image vector

    
09.04.2018 / 19:41