Android How Do I Correctly Get The Value From A Switch?


Answer :

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.


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


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


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable