Android Preference: Show current value in summary

When creating android preference view, I found that the default preference like EditTextPreference does not show the current value as summary (and no way to make them do it). So I made the following class to help:

import android.content.Context;
import android.util.AttributeSet;

public class EditTextPreference extends android.preference.EditTextPreference {

	public EditTextPreference(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	
	@Override
	protected void onDialogClosed(boolean positiveResult) {
		super.onDialogClosed(positiveResult);
		
		setSummary(getSummary());
	}

	@Override
	public CharSequence getSummary() {
		return this.getText();
	}
}
Advertisements

8 responses to “Android Preference: Show current value in summary

  1. Great job. Either this, or like 90% of people deal with registerOnSharedPreferenceChangeListener, unregisterOnSharedPreferenceChangeListener, findPreference and deprecations. Nice and elegant solution, 5 stars.

  2. Nice solution !
    I wanted to add some text (like if it’s an hour you entered it shows 21:00 instead of just 21) and tried to add that info in the xml so that I could use it either for minuts or hours but coudn’t do it. Any idea ?

    • An easy way will be have two different preferences and change the ‘getSummary()’ method of one of them.
      If you want to set it from xml then you have to change more, you have to look at AttributeSet which is passed to the constructor of Preference (warning: you need to do a lot more to accomplish this small task).

Want to share your views? Please do reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s