2

SwitchPreference我有一个SettingsFragment.kt根据它是打开还是关闭来更改图标和标题的。

这是代码:

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
}

但是,此代码有效,假设用户单击SwitchPreference关闭,离开SettingsFragment并返回它。它会显示SwitchPreference关闭,但标题和图标将不正确。正确的图标和标题将是我在else上面声明中的代码。

SwitchPreference用户进入SettingsFragment. 我想检查一下,如果SwitchPreference关闭,我可以以编程方式设置正确的图标和标题。

4

1 回答 1

2

使用布尔键/值对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(this@SettingsFragment.requireContext())

    // Get the preference value
    val isOn: Boolean = sharedPrefs.getBoolean(
        preference.getKey(),
        false // default value
    )
    
    if (isOn) {
        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"
    }       
    
}

确保更改R.xml.settings为您的设置文件名,以及R.string.my_preference_key首选项键。

于 2021-08-21T17:30:56.967 回答