1

I want that my Switch change to checked if some condition is true, else, show a toast informing the user what happen. I'm trying:

switch?.setOnclickListener{
if(condition)   switch!!.isChecked=true
else
//Show toast
}

But i know that condition is false and the switch change to checked. How to do the change of switch only when some condition is true?

mojojojo
  • 33
  • 7

2 Answers2

1

This code should work:

    var condition = true
    if (condition == true) {
        switch.isChecked = true
    } else {
        Toast.makeText(this, "This is a toast", Toast.LENGTH_SHORT).show()
    }

Its also possible that your switch is checked by default, your xml should look something like this:

    <Switch
    android:id="@+id/switch1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false"
    android:text="Switch" />

If one of the tags is android:checked="true", set it to false.

ChocolateChapta
  • 148
  • 2
  • 11
  • Why does this not work for you? Try to set your condition to `condition = false` directly in front of your `if` clause, if it still gets checked, some other code in your project is the reason, else your condition was just wrong. @mojojojo – ChocolateChapta Mar 08 '21 at 15:15
  • UPDATE!. Work fine – mojojojo Apr 02 '21 at 04:14
0

Everything seemed to be working for me.

but I found in a different Question that had a similar problem, that they used

checkBox.setChecked(true)
checkbox.jumpDrawablesToCurrentState()

and it worked for them. does any of it help?

here is the original link: Why CheckBox checked not working with Kotlin programmatically?

Doragon
  • 199
  • 1
  • 10