This blog
entry describes how to use the summary field in a ListPreference to show
its value. This works well. The same technique is also needed for an
EditTextPreference, where the value is entered in a dialog.</p>
This can be done by adding keys for the additional preferences to the array
of preference keys.
private ArrayList<Preference> mPreferences = new ArrayList<Preference>();
private String mPreferenceKeys = new String {
"listPreferenceKey",
"editTextPreferenceKey"
};
private OnSharedPreferenceChangeListener mListener;
The listener that updates the summary area in the Preference needs to
distinguish between ListPreference and a string EditTextPreference. This is
done simply using the instanceof operator.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.filter_preference_screen);
mListener = new OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
for (Preference pref : mPreferences) {
if (pref.getKey().equals(key)) {
if (pref instanceof ListPreference) {
pref.setSummary
;
} else {
pref.setSummary(sharedPreferences.getString(key, "<None>"));
}
break;
}
}
}
};
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.registerOnSharedPreferenceChangeListener(mListener);
for (String prefKey : mPreferenceKeys) {
Preference pref = (Preference) getPreferenceManager().findPreference(prefKey);
mPreferences.add(pref);
mListener.onSharedPreferenceChanged(prefs, prefKey);
}
}
Additionally, the preference listener needs to be unregistered when the
activity is destroyed.
@Override
protected void onDestroy() {
SharedPreferences prefs = getPreferenceManager().getSharedPreferences();
prefs.unregisterOnSharedPreferenceChangeListener(mListener);
super.onDestroy();
}