Tom Darious
Tom Darious

Reputation: 523

How do I check the current state of a SwitchPreference?

I have a SwitchPreference in my SettingsFragment.kt that changes the icon and title depending on if it's on or off.

This is the code for that:

notificationsPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
    val switched = newValue as? Boolean ?: false
    if (switched) {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_active)
        notificationsPreference.title = "Receive Notifications"
    } else {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_off)
        notificationsPreference.title = "Mute Notifications"
    }
    true
}

This code works, however, let's say the user clicks the SwitchPreference to be off, leaves the SettingsFragment and comes back to it. It will show the SwitchPreference off, but the title and icon won't be correct. The correct icon and title would be the code I have in my else statement above.

How do I check the current state of a SwitchPreference before the user enters the SettingsFragment. I want to check it so that if the SwitchPreference is off, I can programmatically set the correct icon and title.

Upvotes: 2

Views: 214

Answers (1)

Zain
Zain

Reputation: 40810

The SwitchPreference maintains the current value in the SharedPreference using a boolean key/value pair.

So, you can do this whenever the PreferenceFragment shown using one of its lifecycle methods like onCreatePreferences()

override fun onCreatePreferences(savedInstanceState: Bundle, rootKey: String) {
    setPreferencesFromResource(
        R.xml.settings,  // Your setting.xml file
        rootKey
    ) 
    
    val preference = findPreference(
        getString(R.string.my_preference_key) // Change this to the preference key set in the settings XML file
        val sharedPrefs =
    PreferenceManager.getDefaultSharedPreferences([email protected]())

    // Get the preference value
    val isOn: Boolean = sharedPrefs.getBoolean(
        preference.getKey(),
        false // default value
    )
    
    if (isOn) {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_active)
        notificationsPreference.title = "Receive Notifications"
    } else {
        notificationsPreference.icon = ContextCompat.getDrawable([email protected](), R.drawable.ic_notifications_off)
        notificationsPreference.title = "Mute Notifications"
    }       
    
}

Make sure to change R.xml.settings to the your settings file name, and also the R.string.my_preference_key to the preference key.

Upvotes: 2

Related Questions