Android 如何正确获取 Switch 的值? [英] Android How do I correctly get the value from a Switch?
本文介绍了Android 如何正确获取 Switch 的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个 Android
应用程序,它使用 切换.
我正在尝试侦听更改并在更改时获取值.
使用开关时我有两个问题:
I'm creating a Android
application which uses a Switch.
I'm trying to listen for changes and get the value when changed.
I have two questions when using switches:
- 我使用什么
动作监听器
? - 如何获取
switch
值?
推荐答案
Switch s = (Switch) findViewById(R.id.SwitchID);
if (s != null) {
s.setOnCheckedChangeListener(this);
}
/* ... */
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Toast.makeText(this, "The Switch is " + (isChecked ? "on" : "off"),
Toast.LENGTH_SHORT).show();
if(isChecked) {
//do stuff when Switch is ON
} else {
//do stuff when Switch if OFF
}
}
提示:isChecked
是新的开关值 [true
或 false
] 而不是旧的.
Hint: isChecked
is the new switch value [true
or false
] not the old one.
这篇关于Android 如何正确获取 Switch 的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文