问题
I am having a few issues with updating the summary line in the SharedPreferences as a preference changes. I have a registered OnSharePreferenceChangeListener in the onResume(), and an unregister of the same in the onPause().
The listener is functioning, and I am able to use the onSharedPreferenceChanges() method. The issue I am having is being able to retrieve the preference there so that I can call setSummary(). I am in Ice Cream Sandwich, and it appears as though the findPreference(key) method is deprecated. So:
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);}
is not functioning, and actually returns null for pref. From the examples I have seen, you need to get a preference to call setSummary() on it, and ideas?
回答1:
You shouldn't use an onSharedPreferenceChangedListener for this.
Instead, use something similar to this.
ListPreference myPreference = (ListPreference) findPreference("preference_key");
myPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (((String)newValue).equals("some_value")) {
preference.setSummary("my summary");
}
}
});
findPreference is not deprecated, but rather you shouldn't be using a PreferenceActivity (that is deprecated). If you only need to support Android 3.0+ then you should switch to PreferenceFragment's, the new method. If you need to support Android 2.1+ then it is fine and you can ignore the warnings.
回答2:
I have been trying to use PreferenceFragment in my code, and I was also seeing findPreference(key) return null. The sample code on the Settings documentation page for using OnSharedPreferenceChangeListener hasn't been fully updated for PreferenceFragment and you'll crash with NullPointerException if you use it verbatim.
I finally figured it out: You have to find the Preference via the PreferenceFragment because of course that's where the preferences are now. Obvious in hindsight. Something like this:
public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener
{
protected SettingsFragment settingsFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
settingsFragment = new SettingsFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, settingsFragment).commit();
}
// ...
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals("your_key")) {
String newValue = sharedPreferences.getString(key, "");
settingsFragment.findPreference(key).setSummary(newValue);
}
}
}
来源:https://stackoverflow.com/questions/11639456/android-updating-sharedpreferences-summary-via-listener