Change Checkbox value without triggering onCheckChanged

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

    I didn't really want to be having to pass the listener in each time we set checked changed, nor using enabled as a way of determining whether we should set the value (what happens in the case we have the switch disabled already when setting the value?)

    Instead I'm making use of tags with an id and a couple of extension methods you can call:

    fun CompoundButton.setOnCheckedWithoutCallingChangeListener(
        listener: (view: CompoundButton, checked: Boolean) -> Unit
    ) {
        setOnCheckedChangeListener { view, checked ->
            if (view.getTag(R.id.compound_button_checked_changed_listener_disabled) != true) {
                listener(view, checked)
            }
        }
        this.setTag(R.id.compound_button_enabled_checked_change_supported, true)
    }
    
    fun CompoundButton.setCheckedWithoutCallingListener(checked: Boolean) {
        check(this.getTag(R.id.compound_button_enabled_checked_change_supported) == true) {
            "Must set listener using `setOnCheckedWithoutCallingChangeListener` to call this method" 
        }
    
        setTag(R.id.compound_button_checked_changed_listener_disabled, true)
        isChecked = checked
        setTag(R.id.compound_button_checked_changed_listener_disabled, false)
    }
    

    Now you can call setCheckedWithoutCallingListener(bool) and it will enforce the correct listener usage.

    You can also still call setChecked(bool) to fire the listener if you still need it

提交回复
热议问题