Monday 18 February 2013

Overriding EditTextPreference

A common requirement for Android settings controls (and something that since ICS is now the preferred style according to the official Android design guide), is for the secondary text (also know as the 'summary text') below the preference name to show the current setting for that preference.

I have seen various solutions on the web for how to achieve this, many are complex and require custom handling code to be written for each preference. A neater and more reusable solution is to override the EditTextPreference class itself. There are various ways to do this to achieve the desired result, but I think overriding getSummary() is the neatest option.

public class MyTextPreference extends EditTextPreference {
    public MyTextPreference(Context context) {
        super(context);
    }

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

    public MyTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    // Override getSummary to return the current value formatted using the default summary string
    @Override
    public CharSequence getSummary() {
        return String.format(super.getSummary().toString(), getText());
    }
}

This solution allows you to specify a format string in the default summary string for example "Cache size is %s MB". The current preference value is then simply formatted using this template. If you want the current setting to be shown raw with no template, simply set the default summary text to "%s".