仅当某些条件为真时如何更改 Switch 状态?

时间:2021-03-07 13:53:07

标签: android kotlin user-interface conditional-statements uiswitch

我希望我的 Switch 更改为检查某些条件是否为真,否则,显示一个通知用户发生了什么的祝酒词。我正在尝试:

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

但我知道条件为假并且开关更改为已选中。仅当某些条件为真时,如何进行 switch 的更改?

2 个答案:

答案 0 :(得分:1)

此代码应该可以工作:

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

也有可能你的开关被默认选中,你的 xml 应该是这样的:

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

如果其中一个标签是 android:checked="true",请将其设置为 false

答案 1 :(得分:0)

一切似乎都对我有用。

但我在另一个问题中发现了他们使用的类似问题

checkBox.setChecked(true)
checkbox.jumpDrawablesToCurrentState()

它对他们有用。有什么帮助吗?

这是原文链接: Why CheckBox checked not working with Kotlin programmatically?

相关问题