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.
The
SwitchPreferencemaintains the current value in theSharedPreferenceusing a boolean key/value pair.So, you can do this whenever the
PreferenceFragmentshown using one of its lifecycle methods likeonCreatePreferences()Make sure to change
R.xml.settingsto the your settings file name, and also theR.string.my_preference_keyto the preference key.