61

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?
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
stackoverflow
  • 18,348
  • 50
  • 129
  • 196

6 Answers6

102
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.

Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
61

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

dmon
  • 30,048
  • 8
  • 87
  • 96
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..
                    }
                }
            });

i hope this will solve your problem

Muhammad Numan
  • 23,222
  • 6
  • 63
  • 80
2

I added this in kotlin

switchImage.setOnCheckedChangeListener { compoundButton: CompoundButton, b: Boolean ->
    if (b) // Do something
    else // Do something
}
hiashutoshsingh
  • 980
  • 2
  • 14
  • 41
0

Kotlin but in More readable Java Style

   videoLoopSwitch.setOnCheckedChangeListener(object : CompoundButton.OnCheckedChangeListener{
                override fun onCheckedChanged(switch: CompoundButton?, isChecked: Boolean) {
                    videoPlayer?.apply {
                        setLooping(isChecked)
                    }
                }
            })
Hitesh Sahu
  • 41,955
  • 17
  • 205
  • 154
0

Try This one

@OnClick({R.id.sw_auto_reload})
void onChangedAutoReload(){
    Switch s = (Switch) findViewById(R.id.sw_auto_reload);
    if (s != null) {
        s.setOnCheckedChangeListener(this);
        s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                paymentSettingsPresenter.onAutoReload(b);
            }
        });
    }
}