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

Asked

Viewed 1,462 times

0

I have a two-button View image, go back and forth. In a gallery of 5 photos I would like to keep changing the image so that one button forward an image and the other back. I know how to do just to jump to a specific image. Can anyone help?

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 carries the first with the position of "i":

img.setImageResource(imagensIds[i]);

And then by clicking the button:

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

If you were going backwards you’d use "i--"

But then it’s up to you to make an if to check if it’s already in the last image so it doesn’t arrive for example i = 3 where there is no index 3 in the image array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.