Android - programmatically change the state of a switch without triggering OnCheckChanged listener

Set the listener to null before calling setCheck() function, and enable it after that, such as the following:

switch.setOnCheckedChangeListener (null);
switch.setChecked(true);
switch.setOnCheckedChangeListener (this);

Reference: Change Checkbox value without triggering onCheckChanged


Well, just before doing things in code with the switch you could just unregister the Listener, then do whatever you need to, and again register the listener.


Every CompoundButton (two states button - on/off) has a pressed state which is true only when a user is pressing the view.

Just add a check in your listener before starting the actual logic:

if(compoundButton.isPressed()) {
    // continue with your listener
}

That way, changing the checked value programmatically won't trigger the unwanted code.

From @krisDrOid answer.