我有一个CheckBoxPreference在一个FragmentPreference。当用户激活该复选框时,我将检查是否安装了应用程序,如果没有,则重新设置false的首选项,然后打开Play Store下载应用程序。
基本上一切都很好,但是我有一个问题要刷新UI。实际上,即使在打开Play Store之前将首选项设置为false,当用户返回时,也会选中该框(片段刚刚暂停并恢复,因此首选项值被忽略)。
有没有办法“刷新”活动或片段?
发布于 2012-08-10 14:10:54
让您的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中AdvancedPreferences示例中的代码片段,用于强制复选框首选项的值。
// Toggle the value of mCheckBoxPreference.
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}https://stackoverflow.com/questions/11903346
复制相似问题