Change Checkbox value without triggering onCheckChanged

前端 未结 19 1104
广开言路
广开言路 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:50

    My interpretation which i think is the easiest
    May be helpful)

    public class ProgrammableSwitchCompat extends SwitchCompat {
    
        public boolean isCheckedProgrammatically = false;
    
        public ProgrammableSwitchCompat(final Context context) {
            super(context);
        }
    
        public ProgrammableSwitchCompat(final Context context, final AttributeSet attrs) {
            super(context, attrs);
        }
    
        public ProgrammableSwitchCompat(final Context context, final AttributeSet attrs, final int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        public void setChecked(boolean checked) {
            isCheckedProgrammatically = false;
            super.setChecked(checked);
        }
    
        public void setCheckedProgrammatically(boolean checked) {
            isCheckedProgrammatically = true;
            super.setChecked(checked);
        }
    }
    

    use it

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean on) {
        if (((ProgrammableSwitchCompat) compoundButton).isCheckedProgrammatically) {
            return;
        }
        //...
        ((ProgrammableSwitchCompat) compoundButton).setCheckedProgrammatically(true);
        //...
        ((ProgrammableSwitchCompat) compoundButton).setCheckedProgrammatically(false);
        //...
    }
    

    use will trigger setChecked(boolean) function
    that is all

    KOTLIN

    class MyCheckBox @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int = R.attr.switchStyle
    ) : AppCompatCheckBox(context, attrs, defStyleAttr) {
    
        var programmatically = false
    
        override fun setChecked(checked: Boolean) {
            programmatically = false
            super.setChecked(checked)
        }
    
        fun setCheckedProgrammatically(checked: Boolean) {
            programmatically = true
            super.setChecked(checked)
        }
    }
    

提交回复
热议问题