你可以实现OnSharedPreferenceChangeListener
这样的东西:
@Override
public void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
// Unregister the listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
//update summary
updatePrefsSummary(sharedPreferences, findPreference(key));
}
如果您使用标准首选项,您可以尝试这样的事情:
/**
* Update summary
*
* @param sharedPreferences
* @param pref
*/
protected void updatePrefsSummary(SharedPreferences sharedPreferences,
Preference pref) {
if (pref == null)
return;
if (pref instanceof ListPreference) {
// List Preference
ListPreference listPref = (ListPreference) pref;
listPref.setSummary(listPref.getEntry());
} else if (pref instanceof EditTextPreference) {
// EditPreference
EditTextPreference editTextPref = (EditTextPreference) pref;
editTextPref.setSummary(editTextPref.getText());
} else if (pref instanceof MultiSelectListPreference) {
// MultiSelectList Preference
MultiSelectListPreference mlistPref = (MultiSelectListPreference) pref;
String summaryMListPref = "";
String and = "";
// Retrieve values
Set<String> values = mlistPref.getValues();
for (String value : values) {
// For each value retrieve index
int index = mlistPref.findIndexOfValue(value);
// Retrieve entry from index
CharSequence mEntry = index >= 0
&& mlistPref.getEntries() != null ? mlistPref
.getEntries()[index] : null;
if (mEntry != null) {
// add summary
summaryMListPref = summaryMListPref + and + mEntry;
and = ";";
}
}
// set summary
mlistPref.setSummary(summaryMListPref);
} else if (pref instanceof RingtonePreference) {
// RingtonePreference
RingtonePreference rtPref = (RingtonePreference) pref;
String uri;
if (rtPref != null) {
uri = sharedPreferences.getString(rtPref.getKey(), null);
if (uri != null) {
Ringtone ringtone = RingtoneManager.getRingtone(
getActivity(), Uri.parse(uri));
pref.setSummary(ringtone.getTitle(getActivity()));
}
}
}
}
如果你使用自定义偏好,你可以做任何事情,你可以覆盖 setSummary(int value)
@Override
public void setSummary(int value) {
setSummary(String.valueOf(value)+" ...." );
}