我有一个SwitchPreference
in my SettingsFragment.kt
根据它是否打开或关闭来更改图标和标题。
这是代码:
notificationsPreference.onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue ->
val switched = newValue as? Boolean ?: false
if (switched) {
notificationsPreference.icon = ContextCompat.getDrawable([email protected] /cdn-cgi/l/email-protection(), R.drawable.ic_notifications_active)
notificationsPreference.title = "Receive Notifications"
} else {
notificationsPreference.icon = ContextCompat.getDrawable([email protected] /cdn-cgi/l/email-protection(), R.drawable.ic_notifications_off)
notificationsPreference.title = "Mute Notifications"
}
true
}
但是,此代码可以工作,假设用户单击SwitchPreference
离开,离开SettingsFragment
并回到它。它将显示SwitchPreference
关闭,但标题和图标不正确。正确的图标和标题将是我的代码else
上面的声明。
如何检查当前状态SwitchPreference
在用户输入之前SettingsFragment
。我想检查一下,以便如果SwitchPreference
关闭后,我可以通过编程方式设置正确的图标和标题。
The 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] /cdn-cgi/l/email-protection())
// Get the preference value
val isOn: Boolean = sharedPrefs.getBoolean(
preference.getKey(),
false // default value
)
if (isOn) {
notificationsPreference.icon = ContextCompat.getDrawable([email protected] /cdn-cgi/l/email-protection(), R.drawable.ic_notifications_active)
notificationsPreference.title = "Receive Notifications"
} else {
notificationsPreference.icon = ContextCompat.getDrawable([email protected] /cdn-cgi/l/email-protection(), R.drawable.ic_notifications_off)
notificationsPreference.title = "Mute Notifications"
}
}
确保改变R.xml.settings
到您的设置文件名,以及R.string.my_preference_key
至首选项键。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)