Android 如何正确获取 Switch 的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10576307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:13:22  来源:igfitidea点击:

Android How do I correctly get the value from a Switch?

androidmodel-view-controlleractionlistener

提问by stackoverflow

I'm creating a Androidapplication which uses a Switch.
I'm trying to listen for changes and get the value when changed.
I have two questions when using switches:

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

  1. What action listenerdo I use?
  2. How do I get the the switchvalue?
  1. 什么action listener适合我?
  2. 我如何获得switch价值?

回答by Kazekage Gaara

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
    }
}

Hint: isCheckedis the new switch value [trueor false] not the old one.

提示:isChecked是新的开关值 [truefalse] 不是旧的。

回答by dmon

Since it extends from CompoundButton(docs), you can use setOnCheckedChangeListener()to listen for changes; use isChecked()to get the current state of the button.

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

回答by Muhammad Numan

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..
                    }
                }
            });

i hope this will solve your problem

我希望这能解决你的问题

回答by hiashutoshsingh

I added this in kotlin

我在 kotlin 中添加了这个

switchImage.setOnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
    if (b) // Do something
    else // Do something
}