#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:

  1. fun CompoundButton.changeValueWithoutTriggeringListener(checked: Boolean, listener: CompoundButton.OnCheckedChangeListener) {
  2. setOnCheckedChangeListener(null)
  3. isChecked = checked
  4. setOnCheckedChangeListener(listener)
  5. }
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:

  1. class SwitchHelper(private val switch: CompoundButton) {
  2. private var listener: CompoundButton.OnCheckedChangeListener? = null
  3. fun setOnCheckedChangeListener(listener: CompoundButton.OnCheckedChangeListener) {
  4. this.listener = listener
  5. switch.setOnCheckedChangeListener(listener)
  6. }
  7. fun changeValueWithoutTriggeringListener(checked: Boolean) {
  8. with(switch) {
  9. setOnCheckedChangeListener(null)
  10. isChecked = checked
  11. setOnCheckedChangeListener(listener)
  12. }
  13. }
  14. }
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