lundi 23 septembre 2019

Android Studio -How can I cycle through my images using a button and if-elseif statements?

So basically I have 5 image files and I've made two buttons to cycle through each image. "Prev" and "Next". And when the cycle reaches the 5th image, on the following "Next" button click, it will go back to the first image.

I have achieved that part, now my problem is my "Prev" cycle, when it reaches the 1st image, after the following "Prev" button click it should cycle back to the 5th image, then the 4th, then the 3rd and so on.

I have implemented a result string to keep track of the values as they are being incremented/decremented, like I said before going forward it works out perfectly, just going backwards I run into some errors.

    /* private ImageView iv1;
       private int imVal; */

public void next(View view) {
        if (imVal == 0) {
            imVal++;
            iv1.setImageResource((R.drawable.n1));
        } else if (imVal == 1) {
            imVal++;
            iv1.setImageResource((R.drawable.n2));
        } else if (imVal == 2) {
            imVal++;
            iv1.setImageResource((R.drawable.n3));
        } else if (imVal == 3) {
            imVal++;
            iv1.setImageResource((R.drawable.n4));
        } else if (imVal == 4) {
            imVal++;
            iv1.setImageResource((R.drawable.n5));
        } else {
            imVal = 0;
            imVal++;
            iv1.setImageResource((R.drawable.n1));
        }
        String result = String.valueOf(imVal);
        tv1.setText(result);
    }

    public void prev(View view) {



   if (imVal == 0) {
            imVal--;
            iv1.setImageResource((R.drawable.n5));
        } else if (imVal == 1) {
            imVal--;
            iv1.setImageResource((R.drawable.n1));
        } else if (imVal == 2) {
            imVal--;
            iv1.setImageResource((R.drawable.n2));
        } else if (imVal == 3) {
            imVal--;
            iv1.setImageResource((R.drawable.n3));
        } else if (imVal == 4) {
            imVal--;
            iv1.setImageResource((R.drawable.n4));
        } else {
            imVal = 4;
        }
    String result = String.valueOf(imVal);
    tv1.setText(result);
}

My n1 image is just a picture of the number 1, and so on for the rest of them. As a cycle through "next", n1 matches my result string. But as I cycle through my "prev" the numbers are all off.

Aucun commentaire:

Enregistrer un commentaire