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

stackoverflow picture stackoverflow · May 14, 2012 · Viewed 84.5k times · Source

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:

  1. What action listener do I use?
  2. How do I get the the switch value?

Answer

Kazekage Gaara picture Kazekage Gaara · May 14, 2012
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: isChecked is the new switch value [true or false] not the old one.