[英]How do I turn SwitchCompat on or off in code
I want to turn a SwitchCompat widget on or off in code.我想在代码中打开或关闭 SwitchCompat 小部件。 I mean like when user changes a SwitchCompat from On to Off or otherwise.
我的意思是当用户将 SwitchCompat 从 On 更改为 Off 或其他时。 I want to do this in code.
我想在代码中做到这一点。 How would I do it?
我该怎么做?
SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);
As with any CompoundButton
, you change the checked state of a SwitchCompat
programmatically via setChecked()
.与任何
CompoundButton
一样,您可以通过setChecked()
以编程方式更改SwitchCompat
的选中状态。
Programatically to change the state of a SwitchCompat control using setChecked()
method.使用
setChecked()
方法以编程方式更改 SwitchCompat 控件的状态。
SwitchCompat switchCompat = (SwitchCompat) findViewById(R.id.switch_compat);
switchCompat.setChecked(true); //checked.
or要么
switchCompat.setChecked(false); //unchecked.
Or you can define the checked state directly inside the layout:或者您可以直接在布局中定义选中状态:
<android.support.v7.widget.SwitchCompat
android:id="@+id/myswitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked=true/>
It is also possible to use switchCompat.isChecked = false
in Kotlin也可以在 Kotlin 中使用
switchCompat.isChecked = false
You can use the setChecked(boolean state)
method of the SwitchCompat.您可以使用 SwitchCompat 的
setChecked(boolean state)
方法。
Kotlin科特林
bind.btSwitch.isChecked = true
if using databinding or:如果使用数据绑定或:
val btSwitch = findViewById<switchCompat>(R.id.specificID)
btSwitch.isChecked = true
accesing via findViewById通过 findViewById 访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.