我有一个CheckBoxPreference
在一个FragmentPreference
中。当用户勾选该复选框时,我会检查是否安装了某个应用程序,如果没有,则将首选项重置为false,并打开 Play Store 下载该应用程序。
基本上一切都正常,但我有一个问题需要刷新UI。实际上,即使我在打开 Play Store 之前将首选项设置为false,当用户回来时,该框仍然被选中(片段刚刚暂停和恢复,因此忽略了首选项值)。
是否有一种方法可以“刷新”活动或片段?
我有一个CheckBoxPreference
在一个FragmentPreference
中。当用户勾选该复选框时,我会检查是否安装了某个应用程序,如果没有,则将首选项重置为false,并打开 Play Store 下载该应用程序。
基本上一切都正常,但我有一个问题需要刷新UI。实际上,即使我在打开 Play Store 之前将首选项设置为false,当用户回来时,该框仍然被选中(片段刚刚暂停和恢复,因此忽略了首选项值)。
是否有一种方法可以“刷新”活动或片段?
让你的PreferenceFragment实现OnSharedPreferenceChangeListener接口。
在onCreate()
中,您可以读取首选项值并相应地设置UI。例如:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource.
addPreferencesFromResource(R.xml.shakesql_app_prefs);
// Initialize pref summary label.
// Get a reference to the application default shared preferences.
SharedPreferences sp = getPreferenceScreen().getSharedPreferences();
// Read the current preference value.
String listVal =
sp.getString(getString(R.string.preference_font_size_key),
getString(R.string.preference_font_size_default));
// Look up the textual description corresponding to the
// preference value and write it into the summary field.
String listDesc = descriptionFromPref(
listVal,
getResources().getStringArray(
R.array.preference_font_size_values),
getResources().getStringArray(
R.array.preference_font_size_labels)
);
if (!TextUtils.isEmpty(listDesc)) {
ListPreference listPref =
(ListPreference) findPreference(getString(R.string.preference_font_size_key));
listPref.setSummary(listDesc);
}
}
然后, 在onSharedPreferenceChanged()
中更新UI。
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);
if (pref instanceof ListPreference) {
// Update display title
// Write the description for the newly selected preference
// in the summary field.
ListPreference listPref = (ListPreference) pref;
CharSequence listDesc = listPref.getEntry();
if (!TextUtils.isEmpty(listDesc)) {
pref.setSummary(listDesc);
}
}
}
以下是来自API Demos中AdvancedPreferences示例的代码片段,用于强制设置复选框偏好设置的值。
// Toggle the value of mCheckBoxPreference.
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}
onSharedPreferenceChanged
,但是sharedPreferences.edit().putBoolean("key", false).commit();
不会刷新UI,这就是我的问题。(与setSummary()
相反)。 - FabiF