Kotlin Extension
/** * @param silent set isSilent property, used to indicate setChecked should not be handled by OnCheckedChangeListener */fun Switch.setChecked(checked: Boolean, silent: Boolean) { if (silent) { if (isChecked != checked) { // use tag to store the state tag = true isChecked = checked } } else { isChecked = checked }}/** * @return true if OnCheckedChangeListener should not handle this callback */val Switch.isSilent: Boolean get() { val value = tag != null if (value) tag = null return value }
Usage
switch.setChecked(true, silent = true)switch.setOnCheckedChangeListener { button, isChecked -> if (!switch.isSilent) { // this callback is not triggered via setChecked(true, silent = true) // do something }}
NOTE: Another solution is to remove OnCheckedChangeListener
before setChecked
and call setOnCheckedChangeListener
after that.