I have setOnCheckedChangeListener
implemented for my checkbox
Is there a way I can call
checkbox.setChecked(false);
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