仅当某些条件为真时如何更改 Switch 状态?
How change Switch state only if some condition is true?
我希望我的 Switch 更改为检查某些条件是否为真,否则,显示祝酒词以告知用户发生了什么。我正在尝试:
switch?.setOnclickListener{
if(condition) switch!!.isChecked=true
else
//Show toast
}
但我知道条件为假,开关变为已选中。如何仅在某些条件为真时才更改开关?
此代码应该有效:
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
。
一切似乎都对我有用。
但我在另一个有类似问题的问题中发现他们使用了
checkBox.setChecked(true)
checkbox.jumpDrawablesToCurrentState()
这对他们很有用。有帮助吗?
原文如下link:
我希望我的 Switch 更改为检查某些条件是否为真,否则,显示祝酒词以告知用户发生了什么。我正在尝试:
switch?.setOnclickListener{
if(condition) switch!!.isChecked=true
else
//Show toast
}
但我知道条件为假,开关变为已选中。如何仅在某些条件为真时才更改开关?
此代码应该有效:
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
。
一切似乎都对我有用。
但我在另一个有类似问题的问题中发现他们使用了
checkBox.setChecked(true)
checkbox.jumpDrawablesToCurrentState()
这对他们很有用。有帮助吗?
原文如下link: