Home > database >  loop for change button value when clicked
loop for change button value when clicked

Time:07-04

i'm trying to use a loop to change the value of my button, but when i run the app and click in the button, he just changes one time and the button stucks, like it's not reseting the button when gets to the last value.

There are only 3 options in the button (Normal, Repeating, Shuffle)

It may be a completely dumb question, but i really don't know what i can do.

var repMode = 0

        binding.btnRepMode.setOnClickListener {
            do{
                repMode  
            }while(repMode < 2)

            when(repMode){
                0 -> normalRep()
                1 -> repeatRep()
                2 -> shuffleRep()
            }
        }

CodePudding user response:

I don't think that doing

do {
  repMode  
} while (repMode < 2)

does what you think it does. A do-while loop will run repeatedly until the while condition is no longer true. This means it will keep incrementing repMode until it reaches 2, then stop. It's not clear if you want it to stop when it gets to 2, or start over.

Stopping at 2 (0-1-2-2-2-2-2...)

If you want to increment repMode but not allow it to be greater than 2 you could use something like this instead

if( repMode < 2 ) {
    repMode
}

or

repMode = (  repMode).coerceAtMost(2)

Starting over (0-1-2-0-1-2-...)

If you want repMode to have a repeating cycle (0-1-2-0-1-2...) rather than getting stuck at "2" then you could use a modulus operator (%) like this:

repMode = (  repMode) % 3

You can test the original code out in a simple unit test very easily in Android Studio - the result is always 2. I highly recommend using small tests and log/print statements to help you solve problems like this when you encounter them.

@Test
fun testDoWhile() {
    var repMode = 0
    do {
        repMode  
    } while (repMode < 2)

    println("TEST repMode = $repMode")
}
  • Related