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:
This will set the summary of your preference to the text of the selected entry.
The original
getSummary()
in ListPreference only works whengetEntries()
,getEntryValues()
anddefaultValue
are pre-populated when the Preference screen loads. So it works fine when you use a static fixed list of items, like a<string-array>
resource.But if you are dynamically generating the
entries
andentryValues
at runtime, you need to ensure that these lists are generated when the Preference screen loads inonCreate()
and also ensure that thedefaultValue
is set. Something like this:SettingsFragment.java
For static lists that are populated with
<string-array>
, just ensure thatandroid:defaultValue="..."
is defined, and that it points to a valid item in the 'values' array. For example:android:defaultValue="Item A Value"
This will ensure that the
android:summary="%s"
will work properly for dynamically generated and static lists.