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(this@SettingsFragment.requireContext(), R.drawable.ic_notifications_active)
notificationsPreference.title = "Receive Notifications"
} else {
notificationsPreference.icon = ContextCompat.getDrawable(this@SettingsFragment.requireContext(), 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.