HelloCW
HelloCW

Reputation: 2235

How can I launch a function when I check a CheckBoxPreference with Kotlin?

The following code display a CheckBox control of CheckBoxPreference in a Preference UI using androidx.preference.PreferenceFragmentCompat.

I hope to a function named myFunction() can be launched when I check the CheckBox control of CheckBoxPreference, how can I do?

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
 
    <CheckBoxPreference
        app:key="checkBoxDisplayPinPrompt"
        app:title="@string/preferencePromptPin"
        app:summary="@string/preferencePromptPinSummary"
        app:defaultValue="false"
    />

</PreferenceScreen>



import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat
import info.dodata.voicerecorder.R


class FragmentPreference : PreferenceFragmentCompat(){

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.mypreference, rootKey)


    }

}

Added Content

To Shay Kin: Thanks!

Your code doesn't work, The Code A get the Error A, and the Code B get the Error B.

Error A

Type mismatch: inferred type is CheckBoxPreference? but CheckBoxPreference was expected

Code A

val checkBox = findPreference("checkBoxDisplayPinPrompt") as CheckBoxPreference
checkBox.setOnPreferenceChangeListener { preference, newValue ->
    if (newValue as Boolean) {
        //  function() your Fonction here
    }

    true
}

Error B

Not enough information to infer type variable T

Code B

 val checkBox = findPreference("checkBoxDisplayPinPrompt")!! as CheckBoxPreference
    checkBox.setOnPreferenceChangeListener { preference, newValue ->
        if (newValue as Boolean) {
            //  function() your Fonction here
        }

        true
    }

Upvotes: 1

Views: 210

Answers (1)

Shay Kin
Shay Kin

Reputation: 2657

You can get your Preference by findPreference("Pref_Name") and you should use setOnPreferenceChangeListener to listen for changes :

I'm using androidx.preference:preference-ktx:1.1.1'

package com.fi.stackoverflow

import android.content.ContentValues
import android.content.ContentValues.TAG
import android.os.Bundle
import android.util.Log
import androidx.preference.CheckBoxPreference
import androidx.preference.PreferenceFragmentCompat

class FragmentPreference : PreferenceFragmentCompat() {

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(R.xml.preference_screen, rootKey)

        val checkBox = findPreference<CheckBoxPreference>("checkBoxDisplayPinPrompt")
        checkBox?.setOnPreferenceChangeListener { preference, newValue ->
            //  function() your Fonction here
            if (newValue as Boolean) {
                Log.e(ContentValues.TAG, "onPreferenceChange: $newValue")
            }
            true
        }
    }
}

Upvotes: 1

Related Questions