I'm learning Kotlin and I'm trying to make two buttons that can be toggled with the following characteristics:
- Button 1 starts as toggled(true) and button 2 starts as untoggled(false).
- If I click on the button that is untoggled, he becomes toggled and the other is untoggled.
- If I click on the button that is toggled, he becomes untoggled and the other is toggled.
- If one button is true the other is false.
- The toggled button is always yellow and the other untoggled is white.
The buttons code:
<ToggleButton
android:id="@+id/button1"
android:background="@color/yellow"
android:text="ToggleButton"
android:textOff="Ton"
android:textOn="Ton"/>
<ToggleButton
android:id="@+id/button2"
android:background="@color/white"
android:text="ToggleButton"
android:textOff="Kg"
android:textOn="Kg"/>
The activity code:
private val btn1 by lazy { findViewById<View>(R.id.button1) as ToggleButton }
private val btn2 by lazy { findViewById<View>(R.id.button2) as ToggleButton }
btn1.setOnClickListener{
btn1.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) { //if btn1 is true he is yellow and btn2 is false and he is white
btn2.isChecked = false
btn1.setBackgroundColor(Color.YELLOW)
btnLoadModeFrac.setBackgroundColor(Color.WHITE)
} else { //if btn1 is false he is white and btn2 is true and he is yellow
btn2.isChecked = true
btn1.setBackgroundColor(Color.WHITE)
btn2.setBackgroundColor(Color.YELLOW)
}
}
}
PROBLEM
The problem here is that, on the first click, I can toggle both button 1 and button 2 (Both are true), even when I set one as false and the other one as true. After that, everything works well.
I tried to set button 1 to true and button 2 to false in my activity before calling the function, but it didn't work either.
Thanks for any help!