#3 Android Switch Switching without triggering the listener

#3 Android Switch Switching without triggering the listener

Sometimes we need to change the calue of a Switch (or SwitchMaterial), without calling the attached listener (to set it programmatically). To achieve this you can write yourself a little handy extension function like this:

fun CompoundButton.changeValueWithoutTriggeringListener(checked: Boolean, listener: CompoundButton.OnCheckedChangeListener) { 
    setOnCheckedChangeListener(null) 
    isChecked = checked 
    setOnCheckedChangeListener(listener) 
}

Unfortunately there is not getter to retrieve the listener, so you will have to store it in a variable and provide it later – or you could write yourself a little helper class like this:

class SwitchHelper(private val switch: CompoundButton) {
    private var listener: CompoundButton.OnCheckedChangeListener? = null

    fun setOnCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener) {
        this.listener = listener
        switch.setOnCheckedChangeListener(listener)
    }

    fun changeValueWithoutTriggeringListener(checked: Boolean) {
        with(switch) {
            setOnCheckedChangeListener(null)
            isChecked = checked
            setOnCheckedChangeListener(listener)
        }
    }
}

 

 

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert