61

我正在创建一个Android使用Switch的应用程序。
我正在尝试侦听更改并在更改时获取值。
使用开关时我有两个问题:

  1. 我用什么action listener
  2. 我如何获得switch价值?
4

5 回答 5

100
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是新的开关值 [truefalse] 不是旧的。

于 2012-05-14T05:23:11.343 回答
61

由于它从CompoundButton( docs ) 扩展而来,您可以使用它setOnCheckedChangeListener() 来监听更改;用于isChecked()获取按钮的当前状态。

于 2012-05-14T00:49:49.810 回答
12
Switch switch = (Switch) findViewById(R.id.Switch2);

switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        ...switch on..
                    } else {
                       ...switch off..
                    }
                }
            });

我希望这能解决你的问题

于 2018-04-01T17:03:08.107 回答
1

我在 kotlin 中添加了这个

switchImage.setOnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
    if (b) // Do something
    else // Do something
}
于 2020-01-25T15:27:03.843 回答
0

Kotlin,但更具可读性的 Java 风格

   videoLoopSwitch.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener{
                override fun onCheckedChanged(switch: CompoundButton?, isChecked: Boolean) {
                    videoPlayer?.apply {
                        setLooping(isChecked)
                    }
                }
            })
于 2020-07-24T11:57:48.877 回答