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

AndroidModel View-ControllerActionlistener

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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.

Solution 2 - Android

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

Solution 3 - Android

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

Solution 4 - Android

I added this in kotlin

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

Solution 5 - Android

Kotlin but in More readable Java Style

   videoLoopSwitch.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener{
                override fun onCheckedChanged(switch: CompoundButton?, isChecked: Boolean) {
                    videoPlayer?.apply {
                        setLooping(isChecked)
                    }
                }
            })

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionstackoverflowView Question on Stackoverflow
Solution 1 - AndroidKazekage GaaraView Answer on Stackoverflow
Solution 2 - AndroiddmonView Answer on Stackoverflow
Solution 3 - AndroidMuhammad NumanView Answer on Stackoverflow
Solution 4 - AndroidhiashutoshsinghView Answer on Stackoverflow
Solution 5 - AndroidHitesh SahuView Answer on Stackoverflow