Change the summary of a ListPreference with the new value (Android)

android, java

Solution

Just set the summary value to `%s` in the xml description.

EDIT: I've tested it on several devices and it doesn't work really. That's strange because according to docs it must work: ListPreference.getSummary().

But it's possible to implement this functionality by oneself. The implementation requires to inherit from the `ListPreference` class:

public class MyListPreference extends ListPreference {
    public MyListPreference(final Context context) {
        this(context, null);
    }

    public MyListPreference(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public CharSequence getSummary() {
        final CharSequence entry = getEntry();
        final CharSequence summary = super.getSummary();
        if (summary == null || entry == null) {
             return null;
        } else {
            return String.format(summary.toString(), entry);
        }
    }

    @Override
    public void setValue(final String value) {
        super.setValue(value);
        notifyChanged();
    }
}

As you can see `MyListPreference` has its own summary field which can contain formatting markers. And when a preference's value changes, `Preference.notifyChanged()` method is called and it causes `MyListPreference.getSummary()` method to be called from `Preference.onBindView()`.

P.S.: This approach hasn't been tested sufficiently so it may contain errors.

Problem

How can I modify the summary of a ListPreference to the new "Entry" string selected by the user (not the entry value) I suppouse its with setOnPreferenceChangeListener() but in ``` new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { return true; } } ``` using ((ListPreference)preference).getEntry() I get the old value (because it isn't changed yet) and newValue.toString() returns the entry value (not the entry text displayed to the user) How can I do it? Thanks in advance

Original source