Change Checkbox value without triggering onCheckChanged

前端 未结 19 997
广开言路
广开言路 2020-11-30 00:18

I have setOnCheckedChangeListener implemented for my checkbox

Is there a way I can call

checkbox.setChecked(false);
         


        
19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-30 00:54

    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!

提交回复
热议问题