I have a ListPreference and I want to show the current entry in the summary. According to the docs for ListPreference.getSummary(), I'm supposed to be able to do this by including %s
in the summary string. Unfortunately, the activity just displays the %s
in the summary.
The XML is pretty standard:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="displayMode"
android:summary="@string/display_mode_summary"
android:title="@string/display_mode"
android:defaultValue="BOTH"
android:entries="@array/displayModes"
android:entryValues="@array/displayModeValues"
/>
</PreferenceScreen>
The value of the string display_mode_summary
is just %s
. (The value "BOTH"
is present in the displayModeValues
array.) If I subclass ListPreference like this:
public final class DisplayModePreference extends ListPreference {
// ...
@Override
public CharSequence getSummary() {
return String.format(super.getSummary().toString(), getEntry());
}
}
then when the preferences activity starts, the current value is correctly interpolated into the summary. But when I click on the preference and select a different value from the dialog, when the dialog closes the summary still shows the now-old value. I need to close the preferences activity and restart it to see the change.
I've tried this in several emulators at different API levels. What do I need to so that the displayed summary always reflects the current value?
You could override "onDialogClosed" as below:
@override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
setSummary(getEntry());
}
}
This will set the summary of your preference to the text of the selected entry.