androidkotlinswitch-statementfragmentswitchpreference

How to check the current state of a SwitchPreference?


I have a SwitchPreferenceCompat and I want to say if Switch preference is enabled show Toast(switch preference is enabled) else it disables again shows a Toast(switch preference is disabled) There were some questions like this but none of them worked for me.

Here is XML:

<PreferenceCategory app:title="عممومی">

    <Preference
        app:key="backUp"
        app:title="بشتیبان گیری آفلاین از اطلاعات" />
     

      <SwitchPreferenceCompat
        app:key="vibrate"
        app:defaultValue="true"
        app:summary="لرزش هنگام انتخاب یک آیتم"
        app:title="لرزش" />

</PreferenceCategory>

And Setting Fragment:

class SettingsFragment : PreferenceFragmentCompat() {

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

Related question


Solution

  • myPref!!.onPreferenceClickListener =
        Preference.OnPreferenceClickListener {
            Toast.makeText(activity, "WORK", Toast.LENGTH_SHORT).show()
            true
        }
    

    You need to replace onPreferenceClickListener by onPreferenceChangeListener

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
    
        val myPref = findPreference<SwitchPreferenceCompat>("vibrate")
    
        myPref?.onPreferenceChangeListener =
           // The callback is triggered whenever the switch preference is changed
            Preference.OnPreferenceChangeListener { pref, newValue ->
    
                if (pref is SwitchPreferenceCompat) {
                    val value = newValue as Boolean
                    if (value) Toast.makeText(requireContext(), "WORK", Toast.LENGTH_SHORT)
                        .show()
                    else Toast.makeText(requireContext(), "OFF", Toast.LENGTH_SHORT).show()
                }
                true
            }
    }