Fab*_*biF 12 android android-preferences android-fragments
我有CheckBoxPreference一个FragmentPreference.当用户激活复选框时,我会检查是否安装了应用程序,如果没有,我会将首选项重置为false,然后打开Play商店下载应用程序.
基本上一切正常,但我有一个问题来刷新UI.实际上,即使我在打开Play商店之前将首选项设置为false ,当用户返回时,也会检查该框(片段刚刚暂停并恢复,因此忽略了首选项值).
有没有办法"刷新"活动或片段?
Spa*_*rky 18
使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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
以下是API演示中AdvancedPreferences示例的代码片段,用于强制复选框首选项的值.
// Toggle the value of mCheckBoxPreference.
if (mCheckBoxPreference != null) {
mCheckBoxPreference.setChecked(!mCheckBoxPreference.isChecked());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11087 次 |
| 最近记录: |