简体   繁体   中英

What is the best way to make a back button that changes the image that's displayed

I'm trying to make an app that has a next and back button that shows different photos, my next button works but the back button does not. I used someone's code I found online for the next button (theirs was just a "change button" button) and altered their code to just be a next button instead. Then tried altering the next button to just do the opposite for the back button but I'm running into problems. I apologize if this is a simple question, I'm new to coding in general and don't have much understanding of most of the concepts. [ This is what I've tried ]( https://i.stack.imgur.com/hRd3K.png )

I tried to make the b2 setOnClickListener just do the opposite of the b1 listener but instead of going back it goes next one photo and then crashes the app. The next button works fine until I click the back button, then the next time I click the next button the app also crashes.

The actual problem is in your indexing. You have 3 images inside your images array. When you press the back button and you check if i == 0 then you set i = 3. There isn't index 3 inside your array since it goes from 0 to 2.

That's when you probably get indexed out of bounds and the app crashes. Try changing

if (i == 0) i = 3;

to

if (i == 0) i = 2;

Also maybe do your operations on 'i' before getting image resource. Like this:

b1!!.setOnClickListener{
   ++i;
   if (i == 3) i = 0;
   iv!!.setImageResource(images[i]);
}


b1!!.setOnClickListener{
       --i;
       if (i == 0) i = 2;
       iv!!.setImageResource(images[i]);
 }

That's why when you press the back button you don't go back but instead go forward. Maybe even that causes the index out of bounds since you actually always save the future index in i and not the current index.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM