I have setOnCheckedChangeListener
implemented for my checkbox
Is there a way I can call
checkbox.setChecked(false);
I found all the above answers way too complicated. Why not just create your own flag with a simple boolean?
Just use a simple flag system with a boolean. Create boolean noListener
. Whenever you want to turn your switch on/off without running any code (in this example, represented as runListenerCode()
, simply set noListener=true
before calling switch.setChecked(false/true)
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean selected) {
if (!noListener) { //If we want to run our code like usual
runListenerCode();
} else { //If we simply want the switch to turn off
noListener = false;
}
});
Very simple solution using simple flags. At the end, we set noListener=false
once again so that our code continues to work. Hope this helps!