How to listen for SwitchCompat widget clicks? I want to execute a few statements when the Switch is toggled.
Looking for an equivalent of
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Do something
}
});
static Boolean isTouched = false;
switchButton.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isTouched = true;
return false;
}
});
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isTouched) {
isTouched = false;
if (isChecked) {
}
else {
}
}
}
});
Try this!
you need only this(the setOnTouchListener is unnecessary):
switchButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked) {
//if 'isChecked' is true do whatever you need...
}
else {
}
}
}
});
With Butterknife SwitchCompat state change
@OnCheckedChanged(R.id.switchCompat)
public void onCheckedChanged(SwitchCompat switchCompat, boolean isChecked) {
Log.i("skh", "check:" + isChecked);
if (isChecked) {
// Log.i("skh","check:"+isChecked);
} else {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With