我有以下问题:
onSharedPreferenceChanged
仅在我第一次更改中的值时调用MultiSelectListPreference
,但再也不会调用。当我重新启动 PrefernceActiviy 时,所有首选项都保留了,并且onSharedPreferenceChanged
只在第一次调用时再次调用。
我做过的事情:
- 我将我
PreferenceActivity
视为“OnSharedPreferenceChangeListener”(我不创建匿名类) - 我在和中注册和注销
this
对象onResume()
onPause
- 我尝试以
SharedPreference
两种方式获得,作为
a) getPreferenceScreen().getSharedPreferences()
a) new SharedPreferences(this)
但两种方式的工作方式完全相同
我究竟做错了什么?
发布代码:
object PreferencesActivity {
final val KEY_AUTO_REFRESH = "preference_auto_refresh"
final val KEY_REFRESH_PERIOD = "preference_refresh_period"
final val KEY_NOTIFICATIONS = "preference_notifications"
final val KEY_AUTO_MARK_AS_READ = "preference_auto_mark_as_read"
final val KEY_CHECKED_RADIO_BUTTON = "preference_checked_radio"
final val KEY_SHOW_SELECTED_ONLY = "preference_show_selected_only"
final val KEY_KEEP_READ_FEEDS = "preference_keep_read_feeds"
private final val DEFAULT_REFRESH_PERIOD = "10"
}
class PreferencesActivity extends SherlockPreferenceActivity with OnSharedPreferenceChangeListener {
private lazy val sharedPreferences = getPreferenceScreen.getSharedPreferences
override def onCreate(savedInstanceState: Bundle) = {
super.onCreate(savedInstanceState)
addPreferencesFromResource(R.xml.preferences)
getSupportActionBar.setDisplayHomeAsUpEnabled(true)
}
override def onResume = {
super.onResume
getPreferenceScreen.getSharedPreferences
.registerOnSharedPreferenceChangeListener(this)
configureRefreshPeriod
configureNotificationsType
}
override def onPause = {
super.onPause
getPreferenceScreen.getSharedPreferences
.unregisterOnSharedPreferenceChangeListener(this)
}
private def configureRefreshPeriod = {
val textViewRefreshPeriod = findPreference(KEY_REFRESH_PERIOD)
textViewRefreshPeriod.setSummary(getNotificationPeriod)
}
private def getNotificationPeriod = {
val refreshPeriodValue = sharedPreferences.getString(KEY_REFRESH_PERIOD, DEFAULT_REFRESH_PERIOD)
val summaryRefreshPeriod_general = getString(R.string.preference_period_summary)
val summaryRefreshPeriod_concrete = String.format(summaryRefreshPeriod_general, refreshPeriodValue.toString)
summaryRefreshPeriod_concrete
}
private def configureNotificationsType = {
val textViewNotifications = findPreference(KEY_NOTIFICATIONS)
textViewNotifications.setSummary(getNotificationKinds)
}
private def getNotificationKinds = {
val notificationsSet = sharedPreferences.getStringSet(KEY_NOTIFICATIONS, new HashSet)
if (!notificationsSet.isEmpty)
getString(R.string.preference_notifications_summary_checked) +
getStringValuesFromSet(notificationsSet)
else
getString(R.string.preference_notifications_summary_unchecked)
}
private def getStringValuesFromSet(notificationsSet: Set[String]) = {
notificationsSet.toArray.mkString(", ")
}
override def onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) =
key match {
case `KEY_REFRESH_PERIOD` => configureRefreshPeriod
case `KEY_NOTIFICATIONS` => configureNotificationsType
case _ =>
}
}
}