Search code examples
kotlinwidgetparameter-passing

Is it possible to pass a widget as a parameter to a function in Kotlin


There are several switches in the app's layout, and when these switches are pressed, the value of sharedPreference is changed to determine whether a specific function is performed. For example, if the funcOnOff switch is off, the voice notification function is off, and when fromOnOff is off, caller information cannot be checked when a notification is received.

I am using several source codes that work almost similarly as below. Is it possible to pass multiple android.widgets as parameters to a function so that these actions can be acted upon as a single function?

var funcOnOff: Switch = findViewById(R.id.func_on_off)
var fromOnOff: Switch = findViewById(R.id.from_on_off)
var timeOnOff: Switch = findViewById(R.id.time_on_off)
var contentOnOff: Switch = findViewById(R.id.content_on_off)

funcOnOff.setOnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            editor.putString("func", "ON")
        } else {
            editor.putString("func", "OFF")
        }
        editor.commit()
    }
    fromOnOff.setOnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            editor.putString("from", "ON")
        } else {
            editor.putString("from", "OFF")
        }
        editor.commit()
    }
    timeOnOff.setOnCheckedChangeListener { buttonView, isChecked ->
        if (isChecked) {
            editor.putString("time", "ON")
        } else {
            editor.putString("time", "OFF")
        }
        editor.commit()
    }

Solution

  • If I understand correctly, you can make a factory method for the OnCheckedChangeListeners.

    fun onCheckedChangedListenerForPreferenceKey(key: String): CompoundButton.OnCheckedChangeListener = { _, isChecked ->
        if (isChecked) {
            editor.putString(key, "ON") // wouldn't using putBoolean be better?
        } else {
            editor.putString(key, "OFF")
        }
        editor.commit()
    }
    

    Then you can do:

    funcOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey("func"))
    fromOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey("from"))
    timeOnOff.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey("time"))
    

    Or you can make a list of pairs of switches to preference keys, and iterate through them:

    listOf(
        funcOnOff to "func"
        fromOnOff to "from"
        timeOnOff to "time"
    ).forEach { (switch, key) -> 
        switch.setOnCheckedChangeListener(onCheckedChangedListenerForPreferenceKey(key))
    }