我有一个SwitchPreference
在我的SettingsFragment.kt
改变图标和标题取决于它是否开启或关闭。
这是代码:
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
}
但是,此代码有效,假设用户单击SwitchPreference
要关闭的,离开SettingsFragment
并返回它。它将显示SwitchPreference
关闭,但标题和图标将不正确。正确的图标和标题将是我在else
上述声明中的代码。
如何SwitchPreference
在用户输入SettingsFragment
. 我想检查一下,如果SwitchPreference
关闭,我可以以编程方式设置正确的图标和标题。
在SwitchPreference
保持在当前值SharedPreference
使用布尔键/值对。
因此,您可以在PreferenceFragment
使用其生命周期方法之一显示时执行此操作,例如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"
}
}
确保更改R.xml.settings
为您的设置文件名,以及R.string.my_preference_key
首选项键。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句