Home > front end >  Do some action onPreferenceChange
Do some action onPreferenceChange

Time:04-16

I can't force Android Studio to compile this. After four days of googling have less knowledge then before... I understand, that something is wrong with setOnPreferenceChangeListener parameter but what?

class MessagesFragment : PreferenceFragmentCompat() {
        private val TAG = "MF"
        override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
            setPreferencesFromResource(R.xml.messages_preferences, rootKey)

            val sw1 = findPreference<SwitchPreference>("switchButton1")
            sw1?.setOnPreferenceChangeListener({ _ ,  isChecked ->
                val message = if (isChecked) "Switch1:ON" else "Switch1:OFF"
                Log.d(TAG, message)

            })
        }
    }

I simply want to see SWITCH1:ON or :OFF in the log....

But Type mismatch: inferred type is Unit but Boolean was expected

CodePudding user response:

OnPreferenceChangeListener is supposed to return a Boolean. The last line of your lambda must evaluate to either true or false. If you make it false, it will reject the preference change, and the value will remain unchanged even though the user clicked it. In most cases, you'll just want to put true.

        sw1?.setOnPreferenceChangeListener { _ ,  isChecked ->
            val message = if (isChecked) "Switch1:ON" else "Switch1:OFF"
            Log.d(TAG, message)
            true
        }

The reason the error message was talking about inferring Unit is that functions that return nothing implicitly return Unit in Kotlin. The last line of your lambda was calling Log.d(), which implicitly returns Unit.

CodePudding user response:

Many thanks to @Tenfour.

First: Don't trust yourself :D

Use !! shows me the main problem -> preference wasn't found.

Second: Id is not the same as KEY

Third - Listener should return True or False

So simple... 4 days vs. 4 minutes... I can rest...

  • Related