Android Switch setChecked Without Trigger OnCheckedChangeListener (Kotlin)

Dec 3, 2019

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.

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.