How do I display the current value of an Android Preference in the Preference summary?
Asked Answered
K

36

477

This must come up very often.

When the user is editing preferences in an Android app, I'd like them to be able to see the currently set value of the preference in the Preference summary.

Example: if I have a Preference setting for "Discard old messages" that specifies the number of days after which messages need to be cleaned up. In the PreferenceActivity I'd like the user to see:

"Discard old messages" <- title

"Clean up messages after x days" <- summary where x is the current Preference value

Extra credit: make this reusable, so I can easily apply it to all my preferences regardless of their type (so that it work with EditTextPreference, ListPreference etc. with minimal amount of coding).

Keratitis answered 10/2, 2009 at 8:2 Comment(0)
H
155

There are ways to make this a more generic solution, if that suits your needs.

For example, if you want to generically have all list preferences show their choice as summary, you could have this for your onSharedPreferenceChanged implementation:

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference pref = findPreference(key);

    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference) pref;
        pref.setSummary(listPref.getEntry());
    }
}

This is easily extensible to other preference classes.

And by using the getPreferenceCount and getPreference functionality in PreferenceScreen and PreferenceCategory, you could easily write a generic function to walk the preference tree setting the summaries of all preferences of the types you desire to their toString representation

Heliport answered 22/5, 2010 at 15:12 Comment(5)
nice solution indeed. only lacks an initializationRonrona
@Ronrona all you have to do is make sure the activity implements OnSharedPreferenceChangeListenerCarding
NB: There is a simpler way, see @Robertas's answer.Trejo
Actually, you can set summary to "%s" for ListPreference, and ListPreference.getSummary() will format the summary with the current selected entry (or "" if none selected).Fatimahfatimid
findPreference(key) is deprecated, is there another way of accessing this?Kennykeno
B
144

Here is my solution... FWIW

package com.example.PrefTest;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;

public class Preferences extends PreferenceActivity implements
        OnSharedPreferenceChangeListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        PreferenceManager.setDefaultValues(Preferences.this, R.xml.preferences,
            false);
        initSummary(getPreferenceScreen());
    }

    @Override
    protected void onResume() {
        super.onResume();
        // Set up a listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // Unregister the listener whenever a key changes
        getPreferenceScreen().getSharedPreferences()
                .unregisterOnSharedPreferenceChangeListener(this);
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
            String key) {
        updatePrefSummary(findPreference(key));
    }

    private void initSummary(Preference p) {
        if (p instanceof PreferenceGroup) {
            PreferenceGroup pGrp = (PreferenceGroup) p;
            for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
                initSummary(pGrp.getPreference(i));
            }
        } else {
            updatePrefSummary(p);
        }
    }

    private void updatePrefSummary(Preference p) {
        if (p instanceof ListPreference) {
            ListPreference listPref = (ListPreference) p;
            p.setSummary(listPref.getEntry());
        }
        if (p instanceof EditTextPreference) {
            EditTextPreference editTextPref = (EditTextPreference) p;
            if (p.getTitle().toString().toLowerCase().contains("password"))
            {
                p.setSummary("******");
            } else {
                p.setSummary(editTextPref.getText());
            }
        }
        if (p instanceof MultiSelectListPreference) {
            EditTextPreference editTextPref = (EditTextPreference) p;
            p.setSummary(editTextPref.getText());
        }
    }
}
Botfly answered 1/12, 2010 at 14:15 Comment(10)
This does work great @EddieB...except that I have a preference screen within a preference screen. Any idea how to reach the inner preference screen and populate those with summary?Coextensive
@Coextensive - change if (p instanceof PreferenceCategory) { PreferenceCategory pCat = (PreferenceCategory) p; to if (p instanceof PreferenceGroup) { final PreferenceGroup pCat = (PreferenceGroup) p;Estellestella
this is working great what if EditTextPreference is android:password="true" it shows the valueVernacularism
How should I modify the code to display summary from the resource (xml) file if no value is defined (i.e. if editTextPref.getText() == "")? How to get summary value at updatePrefSummary? p.getSummary() and editTextPref.getSummary() return already modified values.Susy
Since both PreferenceCategory and PreferenceScreen inherit from PreferenceGroup, I've changed initSummary to handle a PreferenceGroup instead. This avoids the need of another loop in onCreate(). Change in behavior: nested PreferenceScreens now also ge handled recursively.Eyas
for i18n: change the p.getTitle().toString().contains("assword") to p.getKey().equals("your_password_preference_item_key") .. or a a list of them .. or use "contains", as long as you're sure all password-item-keys contain that string and others don't.Landwehr
findPreference(CharSequence key)... This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.Crucible
Last four lines are incorrect and will always throw a ClassCastExceptionBatfowl
In updatePrefSummary the second and third if statements could be changed to else if, since p can only be and instance of one of those preference types.Bop
This works very well. I think it can be improved a little bit with the password fields though. Instead of relying on the title containing the work "password", you could detect the type of the underlying editText's input method. You can do that like this: if( InputType.TYPE_TEXT_VARIATION_PASSWORD == (((EditTextPreference) preference).getEditText().getInputType() & InputType.TYPE_TEXT_VARIATION_PASSWORD)) { }else{ }Probabilism
O
104

Android documentation says one can use a String formatting marker in getSummary():

If the summary has a String formatting marker in it (i.e. "%s" or "%1$s"), then the current entry value will be substituted in its place.

Simply specifying android:summary="Clean up messages after %s days" in ListPreference xml declaration worked for me.

Note: This only works for ListPreference.

Orson answered 30/3, 2012 at 6:47 Comment(9)
Someone correct me if I'm wrong, but the documentation for getSummary() states that it was added in API level 1. Are you implying that the behavior was different when first released?Wacker
Unfortunately, this only works for ListPreference. I want the same behavior for EditTextPreference. It's surprising that Google hasn't added this for all DialogPreferences.Crowson
Plus, I does not work as long as the value has not been set - on the first ever call of the Preference activity, it displays just %s which is really dumb.Lindly
@Lindly That can be fixed by specifying the default value in your xml like android:defaultValue="0" in your ListPreference. This is the most sensible answer and works for me.Schiro
@Mohit Singh / @Zordid, on Lollipop API 22, the defaultValue and the %s do not work. On other versions, generally, it works though. Any solution please? I sure do not want to write a custom class for this. Unbelievable that Google makes the most trivial of tasks such a pain.Cyclotron
which api versions does this work for? I'm testing against api10 (my app supports very old devices) and %s isn't working as expected, but it works on newer versions.Publicize
From here: "The format specifiers for general, character, and numeric types have the following syntax:" %[argument_index$][flags][width][.precision]conversionBursary
This is the answer that I was looking for. At least if you're using a ListPreference, this is much simpler/cleaner than the other solutions (and it follows the standard API which is always preferable for forward-compatibility).Becoming
This is deprecated in API 29Mailer
O
84

If you use PreferenceFragment, this is how I solved it. It's self explanatory.

public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      addPreferencesFromResource(R.xml.settings);
      getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onResume() {
      super.onResume();
      for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
        Preference preference = getPreferenceScreen().getPreference(i);
        if (preference instanceof PreferenceGroup) {
          PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
          for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
            Preference singlePref = preferenceGroup.getPreference(j);
            updatePreference(singlePref, singlePref.getKey());
          }
        } else {
          updatePreference(preference, preference.getKey());
        }
      }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
      updatePreference(findPreference(key), key);
    }

    private void updatePreference(Preference preference, String key) {
      if (preference == null) return;
      if (preference instanceof ListPreference) {
        ListPreference listPreference = (ListPreference) preference;
        listPreference.setSummary(listPreference.getEntry());
        return;
      }
      SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
      preference.setSummary(sharedPrefs.getString(key, "Default"));
    }
  }
Oleograph answered 14/9, 2013 at 23:45 Comment(11)
This solution needs more votes... It bugs me that the examples on the developer site SHOW this being done, but omit it completely.Antietam
FWIW, I used this solution to add this to my app. In reference to another answer, I had to add specific checks for certain keys in order to do a string format, which is defined in the strings.xml resource. This seems cumbersome, but its the only way I can find to mimic the system settings, which does this as well.Antietam
To get EditTextPreferences also updated add this to updatePreference CODE if (preference instanceof EditTextPreference) { EditTextPreference editTextPref = (EditTextPreference) preference; preference.setSummary(editTextPref.getText()); } thanks @BotflyJaguarundi
Where you call unregisterOnSharedPreferenceChangeListener ?Bitters
@Bitters it should just be in onDestroy (the corresponding method to where it was registered)..Rinderpest
findPreference(CharSequence key) This method was deprecated in API level 11. This function is not relevant for a modern fragment-based PreferenceActivity.Crucible
@Crucible You're using a PreferenceActivity, not a PreferenceFragment like in the answer.Tsui
@Dan Hulme--that's a quote found hereCrucible
@Crucible I'm well aware of what you're quoting. It's telling you not to use PreferenceActivity.findPreference (and several other methods), because Google wants you to switch to the technique shown in this answer, which uses PreferenceFragment.findPreference instead.Tsui
I'd like to point out that the key parameter in updatePreference is redundant as you can just call getKey() on your preference objectInternationale
Great solution. Complete, and it works. Not sure why this one doesn't get more upvotes. Thanks @OleographNovak
P
33

My option is to extend ListPreference and it's clean:

public class ListPreferenceShowSummary extends ListPreference {

    private final static String TAG = ListPreferenceShowSummary.class.getName();

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

    public ListPreferenceShowSummary(Context context) {
        super(context);
        init();
    }

    private void init() {

        setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

            @Override
            public boolean onPreferenceChange(Preference arg0, Object arg1) {
                arg0.setSummary(getEntry());
                return true;
            }
        });
    }

    @Override
    public CharSequence getSummary() {
        return super.getEntry();
    }
}

Then you add in your settings.xml:

<yourpackage.ListPreferenceShowSummary
    android:key="key" android:title="title"
    android:entries="@array/entries" android:entryValues="@array/values"
    android:defaultValue="first value"/>
Photocell answered 4/11, 2011 at 3:10 Comment(3)
I made a solution based on this. In my solution I have a method to set an array of entrySummaries instead of using the entries strings in both the menu and the summaries. There is one problem here: getEntry() returns the previous value not the new one.Riva
Actually is init() even nescessary? I have just overidden getSummary() and it seems to work prefectly!Pastiche
The init() function is necessary to update the summary when the user changes that preference. Without it, it will just stay whatever the entry was initially.Burmaburman
D
23

You can override default Preference classes and implement the feature.

public class MyListPreference extends ListPreference  {
    public MyListPreference(Context context) { super(context); }
    public MyListPreference(Context context, AttributeSet attrs) { super(context, attrs); }
    @Override
    public void setValue(String value) {
        super.setValue(value);
        setSummary(getEntry());
    }
}

Later in you xml you can use custom preference like

<your.package.name.MyListPreference 
    android:key="noteInterval"
    android:defaultValue="60"
    android:title="Notification Interval"
    android:entries="@array/noteInterval"
    android:entryValues="@array/noteIntervalValues"
    />
Dominickdominie answered 23/7, 2012 at 9:29 Comment(1)
Excellent simple method. Just watch out for things like % in the getEntry string as they might cause issues (or they did for me)Lecce
C
21

After several hours I've been spent to solve such problem I've implemented this code:

[UPDATE: the final version listing]

public class MyPreferencesActivity extends PreferenceActivity {
    ...
    ListPreference m_updateList;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        m_updateList = (ListPreference) findPreference(getString(R.string.pref_update_interval_key));
        String currentValue = m_updateList.getValue();
        if (currentValue == null) {
            m_updateList.setValue((String)m_updateList.getEntryValues()[DEFAULT_UPDATE_TIME_INDEX]);
            currentValue = m_updateList.getValue();
        }
        updateListSummary(currentValue);    

        m_updateList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                updateListSummary(newValue.toString());
                return true;
            }       
        });     
    }

    private void updateListSummary(String newValue) {
        int index = m_updateList.findIndexOfValue(newValue);
        CharSequence entry = m_updateList.getEntries()[index];
        m_updateList.setSummary(entry);
    }
}

That was the only solution that worked for me fine. Before I've tried to subclass from ListPreferences and to implement android:summary="bla bla bla %s". Neither worked.

Claw answered 26/6, 2012 at 15:8 Comment(3)
Your way is more clear and uses less code then others. The top answers works using "proxy" - preferences manager. It's not so clear as listening for direct changes in list.Bixby
@Subtle Fox, Neat solution. just curious if you did 'setDefaultValue()' then why check for (ss==null)Cherey
Because setDefaultValue() shouldn't be there :) I've put this code before refactoringClaw
A
21

Maybe like ListPreference: Modify getSummary to get what you want:

package your.package.preference;

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

public class EditTextPreference extends android.preference.EditTextPreference{
        public EditTextPreference(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

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

        public EditTextPreference(Context context) {
            super(context);
        }

        @Override
        public CharSequence getSummary() {
            if(super.getSummary() == null) return null;

            String summary = super.getSummary().toString();
            return String.format(summary, getText());
        }
    }

And use this in your xml:

<your.package.EditTextPreference
                android:key="pref_alpha"
                android:summary="Actual value: %s"
                android:title="Title"
                android:defaultValue="default"
                />

So you are able to write a summary with %s instead of the actual value.

Aminaamine answered 1/8, 2014 at 15:9 Comment(2)
@Aminaamine @serv-inc At least with a subclass of android.support.v7.preference.EditTextPreference, this does not update the summary when the preference is changed, only when the preferences activity is created. A way around this without implementing OnSharedPreferenceChangeListener.onSharedPreferenceChanged in the preferences fragment class is to also override android.support.v7.preference.EditTextPreference.setText(String text): @Override public void setText(String text) { super.setText(text); this.setSummary(this.getText()); }Casmey
@PointedEars: done. But this also seems to be a copy of https://mcmap.net/q/79933/-how-do-i-display-the-current-value-of-an-android-preference-in-the-preference-summaryNonproductive
T
18

This is the code you need to set the summary to the chosen value. It also sets the values on startup and respects the default values, not only on change. Just change "R.layout.prefs" to your xml-file and extend the setSummary-method to your needs. It actually is only handling ListPreferences, but it is easy to customize to respect other Preferences.

package de.koem.timetunnel;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;

public class Prefs 
    extends PreferenceActivity 
    implements OnSharedPreferenceChangeListener {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);

       this.addPreferencesFromResource(R.layout.prefs);
       this.initSummaries(this.getPreferenceScreen());

       this.getPreferenceScreen().getSharedPreferences()
           .registerOnSharedPreferenceChangeListener(this);
    }

  /**
    * Set the summaries of all preferences
    */
  private void initSummaries(PreferenceGroup pg) {
      for (int i = 0; i < pg.getPreferenceCount(); ++i) {
          Preference p = pg.getPreference(i);
          if (p instanceof PreferenceGroup)
              this.initSummaries((PreferenceGroup) p); // recursion
          else
              this.setSummary(p);
      }
  }

  /**
    * Set the summaries of the given preference
    */
  private void setSummary(Preference pref) {
      // react on type or key
      if (pref instanceof ListPreference) {
          ListPreference listPref = (ListPreference) pref;
          pref.setSummary(listPref.getEntry());
      }
  }

  /**
    * used to change the summary of a preference
    */
  public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
     Preference pref = findPreference(key);
     this.setSummary(pref);
  }

  // private static final String LOGTAG = "Prefs";
}

koem

Trevethick answered 10/11, 2010 at 18:14 Comment(2)
Thanks a lot! I created a class from this, giving the resource id as an argument to the onCreate() -- that way it was a one line change to my settings screens to have them show the values in summary.Vyky
BTW: Note that non-persistent preferences will not get updated using this system. Changes to them must be listened using the setOnPreferenceChangeListener(Preference.OnPreferenceChangeListener onPreferenceChangeListener)-method of individual Preferences.Vyky
F
13

According to Android docs you can use app:useSimpleSummaryProvider="true" in ListPreference and EditTextPreference components.

Fredkin answered 29/8, 2019 at 6:8 Comment(2)
This should actually be the accepted answer, if you use androidx.preference.EditTextPreferenceRuthenium
Actually this makes me wonder why this isn't enabled by default.Granophyre
C
12

For EditTextPreference:

public class MyEditTextPreference extends EditTextPreference {
    public MyEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

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

    @Override
    public void setText(String text) {
        super.setText(text);
        setSummary(text);
    }
}
Cumberland answered 20/2, 2014 at 11:46 Comment(0)
O
11

Actually, CheckBoxPreference does have the ability to specify a different summary based on the checkbox value. See the android:summaryOff and android:summaryOn attributes (as well as the corresponding CheckBoxPreference methods).

Orme answered 3/9, 2010 at 18:1 Comment(0)
G
11

If someone is still looking for answers to this, you should check out thirtythreefortys answer.

<ListPreference
    android:key="pref_list"
    android:title="A list of preferences"
    android:summary="%s"
    android:entries="@array/pref_list_entries"
    android:entryValues="@array/pref_list_entries_values"
    android:defaultValue="0" />

Android will replace %s with the current string value of the preference, as displayed by the ListPreference's picker.

Glyn answered 27/7, 2015 at 9:58 Comment(2)
Works. This is the easiest and best solution today.Fair
Note that the "%s" can be placed anywhere in your summary string. And yes, that includes resource strings!Travail
M
7

Thanks for this tip!

I have one preference screen and want to show the value for each list preference as the summary.

This is my way now:

public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
}

@Override
protected void onResume() {
    super.onResume();

    // Set up initial values for all list preferences
    Map<String, ?> sharedPreferencesMap = getPreferenceScreen().getSharedPreferences().getAll();
    Preference pref;
    ListPreference listPref;
    for (Map.Entry<String, ?> entry : sharedPreferencesMap.entrySet()) {
        pref = findPreference(entry.getKey());
        if (pref instanceof ListPreference) {
            listPref = (ListPreference) pref;
            pref.setSummary(listPref.getEntry());
        }
    }

    // Set up a listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}

@Override
protected void onPause() {
    super.onPause();

    // Unregister the listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);    
}

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    Preference pref = findPreference(key);

    if (pref instanceof ListPreference) {
        ListPreference listPref = (ListPreference) pref;
        pref.setSummary(listPref.getEntry());
    }
}

This works for me, but I'm wondering what is the best solution (performance, stability, scalibility): the one Koem is showing or this one?

Mig answered 21/11, 2010 at 15:17 Comment(0)
S
7

I've seen all voted answers show how to set the summary with the exact current value, but the OP wanted also something like:

"Clean up messages after x days"* <- summary where x is the current Preference value

Here is my answer for achieving that

As per the documentation on ListPreference.getSummary():

Returns the summary of this ListPreference. If the summary has a String formatting marker in it (i.e. "%s" or "%1$s"), then the current entry value will be substituted in its place.

However, I tried this on several devices and it doesn't seem to work. With some research, I found a good solution in this answer. It simply consists of extending every Preference you use and override getSummary() to work as specified by Android documentation.

Sulfapyridine answered 18/5, 2012 at 9:55 Comment(2)
It does seem to work initially, but when you choose a new value it doesn't automatically update until you do something to invalidate the whole activity and cause it to redraw. I'm on Android 4.0.4.Varicelloid
Would be nice if Google could add a formatting string to the preference object.Antietam
H
6

Thanks, Reto, for the detailed explanation!

In case this is of any help to anyone, I had to change the code proposed by Reto Meier to make it work with the SDK for Android 1.5

@Override
protected void onResume() {
    super.onResume();

    // Setup the initial values
    mListPreference.setSummary("Current value is " + mListPreference.getEntry().toString()); 

    // Set up a listener whenever a key changes            
    ...
}

The same change applies for the callback function onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)

Cheers,

Chris

Hein answered 28/5, 2010 at 21:40 Comment(0)
G
5

In Android Studio, open "root_preferences.xml", select Design mode. Select the desired EditTextPreference preference, and under "All attributes", look for the "useSimpleSummaryProvider" attribute and set it to true. It will then show the current value.

Ghat answered 12/12, 2019 at 19:1 Comment(1)
duplicate answer, but i like this solutionSilas
J
4

I solved the issue with the following descendant of ListPreference:

public class EnumPreference extends ListPreference {

    public EnumPreference(Context aContext, AttributeSet attrs) {
        super(aContext,attrs);
    }

    @Override
    protected View onCreateView(ViewGroup parent) {
        setSummary(getEntry());
        return super.onCreateView(parent);
    }

    @Override
    protected boolean persistString(String aNewValue) {
        if (super.persistString(aNewValue)) {
            setSummary(getEntry());
            notifyChanged();
            return true;
        } else {
            return false;
        }
    }
}

Seems to work fine for me in 1.6 up through 4.0.4.

Jopa answered 4/7, 2012 at 22:35 Comment(0)
P
4
public class ProfileManagement extends PreferenceActivity implements
OnPreferenceChangeListener {
    EditTextPreference screenName;
    ListPreference sex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.layout.profile_management);

            screenName = (EditTextPreference) findPreference("editTextPref");
            sex = (ListPreference) findPreference("sexSelector");

            screenName.setOnPreferenceChangeListener(this);
            sex.setOnPreferenceChangeListener(this);

    }   

    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
        preference.setSummary(newValue.toString());
        return true;
    }
}
Pevzner answered 27/4, 2013 at 12:2 Comment(0)
A
3

If you only want to display the plain text value of each field as its summary, the following code should be the easiest to maintain. It requires only two changes (lines 13 and 21, marked with "change here"):

package com.my.package;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;

public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {

    private final String[] mAutoSummaryFields = { "pref_key1", "pref_key2", "pref_key3" }; // change here
    private final int mEntryCount = mAutoSummaryFields.length;
    private Preference[] mPreferenceEntries;

    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences_file); // change here
        mPreferenceEntries = new Preference[mEntryCount];
        for (int i = 0; i < mEntryCount; i++) {
            mPreferenceEntries[i] = getPreferenceScreen().findPreference(mAutoSummaryFields[i]);
        }
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onResume() {
        super.onResume();
        for (int i = 0; i < mEntryCount; i++) {
            updateSummary(mAutoSummaryFields[i]); // initialization
        }
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); // register change listener
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); // unregister change listener
    }

    private void updateSummary(String key) {
        for (int i = 0; i < mEntryCount; i++) {
            if (key.equals(mAutoSummaryFields[i])) {
                if (mPreferenceEntries[i] instanceof EditTextPreference) {
                    final EditTextPreference currentPreference = (EditTextPreference) mPreferenceEntries[i];
                    mPreferenceEntries[i].setSummary(currentPreference.getText());
                }
                else if (mPreferenceEntries[i] instanceof ListPreference) {
                    final ListPreference currentPreference = (ListPreference) mPreferenceEntries[i];
                    mPreferenceEntries[i].setSummary(currentPreference.getEntry());
                }
                break;
            }
        }
    }

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        updateSummary(key);
    }

}
Admonish answered 28/12, 2012 at 4:29 Comment(0)
J
3

Here's my solution:

Build a preference type 'getter' method.

protected String getPreference(Preference x) {
    // https://mcmap.net/q/81111/-how-to-check-type-of-variable-in-java
    if (x instanceof CheckBoxPreference)
        return "CheckBoxPreference";
    else if (x instanceof EditTextPreference)
        return "EditTextPreference";
    else if (x instanceof ListPreference)
        return "ListPreference";
    else if (x instanceof MultiSelectListPreference)
        return "MultiSelectListPreference";
    else if (x instanceof RingtonePreference)
        return "RingtonePreference";
    else if (x instanceof SwitchPreference)
        return "SwitchPreference";
    else if (x instanceof TwoStatePreference)
        return "TwoStatePreference";
    else if (x instanceof DialogPreference) // Needs to be after ListPreference
        return "DialogPreference";
    else
        return "undefined";
}

Build a 'setSummaryInit' method.

public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
        Log.i(TAG, "+ onSharedPreferenceChanged(prefs:" + prefs + ", key:" + key + ")");
        if( key != null ) {
            updatePreference(prefs, key);
            setSummary(key);
        } else {
            Log.e(TAG, "Preference without key!");
        }
        Log.i(TAG, "- onSharedPreferenceChanged()");
    }

    protected boolean setSummary() {
        return _setSummary(null);
    }
    
    protected boolean setSummary(String sKey) {
        return _setSummary(sKey);
    }
    
    private boolean _setSummary(String sKey) {
        if (sKey == null) Log.i(TAG, "Initializing");
        else Log.i(TAG, sKey);
        
        // Get Preferences
        SharedPreferences sharedPrefs = PreferenceManager
                .getDefaultSharedPreferences(this);

        // Iterate through all Shared Preferences
        // https://mcmap.net/q/81112/-how-to-iterate-through-all-keys-of-shared-preferences
        Map<String, ?> keys = sharedPrefs.getAll();
        for (Map.Entry<String, ?> entry : keys.entrySet()) {
            String key = entry.getKey();
            // Do work only if initializing (null) or updating specific preference key
            if ( (sKey == null) || (sKey.equals(key)) ) {
                String value = entry.getValue().toString();
                Preference pref = findPreference(key);
                String preference = getPreference(pref);
                Log.d("map values", key + " | " + value + " | " + preference);
                pref.setSummary(key + " | " + value + " | " + preference);
                if (sKey != null) return true;
            }
        }
        return false;
    }

    private void updatePreference(SharedPreferences prefs, String key) {
        Log.i(TAG, "+ updatePreference(prefs:" + prefs + ", key:" + key + ")");
        Preference pref = findPreference(key);
        String preferenceType = getPreference(pref);
        Log.i(TAG, "preferenceType = " + preferenceType);
        Log.i(TAG, "- updatePreference()");
    }

Initialize

Create public class that PreferenceActivity and implements OnSharedPreferenceChangeListener

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    PreferenceManager.setDefaultValues(this, R.xml.global_preferences,
    false);
    this.addPreferencesFromResource(R.xml.global_preferences);
    this.getPreferenceScreen().getSharedPreferences()
        .registerOnSharedPreferenceChangeListener(this);
}

protected void onResume() {
    super.onResume();
    setSummary();
}
Juliettejulina answered 15/7, 2013 at 20:24 Comment(0)
M
3

Simply:

listPreference.setSummary("%s");
Myocarditis answered 6/8, 2015 at 5:5 Comment(0)
C
3

FYI:

findPreference(CharSequence key)
This method was deprecated in API level 11. This function is not relevant
for a modern fragment-based PreferenceActivity.

All the more reason to look at the very slick Answer of @ASD above (source found here) saying to use %s in android:summary for each field in preferences.xml. (Current value of preference is substituted for %s.)

enter image description here

<ListPreference
 ...        
 android:summary="Length of longest word to return as match is %s"
 ...
 />
Crucible answered 6/9, 2015 at 20:3 Comment(0)
C
3

Since in androidx Preference class has the SummaryProvider interface, it can be done without OnSharedPreferenceChangeListener. Simple implementations are provided for EditTextPreference and ListPreference. Building on EddieB's answer it can look like this. Tested on androidx.preference:preference:1.1.0-alpha03.

package com.example.util.timereminder.ui.prefs;

import android.os.Bundle;

import com.example.util.timereminder.R;

import androidx.preference.EditTextPreference;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceGroup;

/**
 * Displays different preferences.
 */
public class PrefsFragmentExample extends PreferenceFragmentCompat {

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        addPreferencesFromResource(R.xml.preferences);

        initSummary(getPreferenceScreen());
    }

    /**
     * Walks through all preferences.
     *
     * @param p The starting preference to search from.
     */
    private void initSummary(Preference p) {
        if (p instanceof PreferenceGroup) {
            PreferenceGroup pGrp = (PreferenceGroup) p;
            for (int i = 0; i < pGrp.getPreferenceCount(); i++) {
                initSummary(pGrp.getPreference(i));
            }
        } else {
            setPreferenceSummary(p);
        }
    }

    /**
     * Sets up summary providers for the preferences.
     *
     * @param p The preference to set up summary provider.
     */
    private void setPreferenceSummary(Preference p) {
        // No need to set up preference summaries for checkbox preferences because
        // they can be set up in xml using summaryOff and summary On
        if (p instanceof ListPreference) {
            p.setSummaryProvider(ListPreference.SimpleSummaryProvider.getInstance());
        } else if (p instanceof EditTextPreference) {
            p.setSummaryProvider(EditTextPreference.SimpleSummaryProvider.getInstance());
        }
    }
}
Catullus answered 16/2, 2019 at 11:10 Comment(0)
D
2

Here,all these are cut from Eclipse sample SettingsActivity. I have to copy all these too much codes to show how these android developers choose perfectly for more generalized and stable coding style.

I left the codes for adapting the PreferenceActivity to tablet and greater API.

public class SettingsActivity extends PreferenceActivity {

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    setupSummaryUpdatablePreferencesScreen();
}

private void setupSummaryUpdatablePreferencesScreen() {

    // In the simplified UI, fragments are not used at all and we instead
    // use the older PreferenceActivity APIs.

    // Add 'general' preferences.
    addPreferencesFromResource(R.xml.pref_general);

    // Bind the summaries of EditText/List/Dialog preferences to
    // their values. When their values change, their summaries are updated
    // to reflect the new value, per the Android Design guidelines.
    bindPreferenceSummaryToValue(findPreference("example_text"));
    bindPreferenceSummaryToValue(findPreference("example_list"));
}

/**
 * A preference value change listener that updates the preference's summary
 * to reflect its new value.
 */
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {

    private String TAG = SettingsActivity.class.getSimpleName();

    @Override
    public boolean onPreferenceChange(Preference preference, Object value) {
        String stringValue = value.toString();

        if (preference instanceof ListPreference) {
            // For list preferences, look up the correct display value in
            // the preference's 'entries' list.
            ListPreference listPreference = (ListPreference) preference;
            int index = listPreference.findIndexOfValue(stringValue);

            // Set the summary to reflect the new value.
            preference.setSummary(
                index >= 0
                ? listPreference.getEntries()[index]
                : null);
        } else {
            // For all other preferences, set the summary to the value's
            // simple string representation.
            preference.setSummary(stringValue);
        }
        Log.i(TAG, "pref changed : " + preference.getKey() + " " + value);
        return true;
    }
};

/**
 * Binds a preference's summary to its value. More specifically, when the
 * preference's value is changed, its summary (line of text below the
 * preference title) is updated to reflect the value. The summary is also
 * immediately updated upon calling this method. The exact display format is
 * dependent on the type of preference.
 *
 * @see #sBindPreferenceSummaryToValueListener
 */

private static void bindPreferenceSummaryToValue(Preference preference) {
    // Set the listener to watch for value changes.
    preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

    // Trigger the listener immediately with the preference's
    // current value.
    sBindPreferenceSummaryToValueListener.onPreferenceChange(preference,
                                                             PreferenceManager
                                                             .getDefaultSharedPreferences(preference.getContext())
                                                             .getString(preference.getKey(), ""));
}

}

xml/pref_general.xml

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by the activity code. -->
<EditTextPreference
android:capitalize="words"
android:defaultValue="@string/pref_default_display_name"
android:inputType="textCapWords"
android:key="example_text"
android:maxLines="1"
android:selectAllOnFocus="true"
android:singleLine="true"
android:title="@string/pref_title_display_name" />

<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog todismiss it.-->
<!-- NOTE: ListPreference's summary should be set to its value by the activity code. -->
<ListPreference
android:defaultValue="-1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:key="example_list"
android:negativeButtonText="@null"
android:positiveButtonText="@null"
android:title="@string/pref_title_add_friends_to_messages" />

</PreferenceScreen>

values/strings_activity_settings.xml

<resources>
<!-- Strings related to Settings -->

<!-- Example General settings -->

<string name="pref_title_display_name">Display name</string>
<string name="pref_default_display_name">John Smith</string>

<string name="pref_title_add_friends_to_messages">Add friends to messages</string>
<string-array name="pref_example_list_titles">
<item>Always</item>
<item>When possible</item>
<item>Never</item>
</string-array>
<string-array name="pref_example_list_values">
<item>1</item>
<item>0</item>
<item>-1</item>
</string-array>
</resources>

NOTE: Actually I just want to comment like "Google's sample for PreferenceActivity is also interesting". But I haven't enough reputation points.So please don't blame me.

(Sorry for bad English)

Dor answered 14/12, 2013 at 18:7 Comment(0)
D
2

You have to use bindPreferenceSummaryToValue function on the onCreate method.

Example:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Add 'general' preferences, defined in the XML file
        addPreferencesFromResource(R.xml.pref_general);

        // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
        // updated when the preference changes.
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
        bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
    }

See lesson 3 on Udacity Android Course: https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1643578599/m-1643578601

Dissipate answered 5/12, 2015 at 9:0 Comment(0)
D
2

For EditTextPreference:

I came to this solution, of course, just if you need particular edittextpreference but you could do this with every Preference:

............

private static final String KEY_EDIT_TEXT_PREFERENCE2 = "on_a1";
public static  String value = "";

............

private void updatePreference(Preference preference, String key) {

            if (key.equals(KEY_EDIT_TEXT_PREFERENCE2)) {
                preference = findPreference(key);
                if (preference instanceof EditTextPreference) {
                    editTextPreference = (EditTextPreference) preference;
                    editTextPreference.setSummary(editTextPreference.getText());
                    value = editTextPreference.getText().toString();
                    return;
                }
                SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
                preference.setSummary(sharedPrefs.getString(KEY_EDIT_TEXT_PREFERENCE2, ""));

            }
}

Then in onResume();

@Override
        public void onResume() {
            super.onResume();

            SharedPreferences etext = getPreferenceManager().getSharedPreferences();
            String str = etext.getString("value", "");
            editTextPreference = (EditTextPreference) findPreference(KEY_EDIT_TEXT_PREFERENCE2);
            editTextPreference.setText(str);
            editTextPreference.setSummary(editTextPreference.getText());

            getPreferenceScreen().getSharedPreferences()
                    .registerOnSharedPreferenceChangeListener(this);
        }

In:

@Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            updatePreference(findPreference(key), key);
}
Dedra answered 13/1, 2016 at 11:42 Comment(0)
T
2

My solution is to create a custom EditTextPreference, used in XML like this: <com.example.EditTextPreference android:title="Example Title" />

EditTextPreference.java:-

package com.example;

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

public class EditTextPreference extends android.preference.EditTextPreference
{
    public EditTextPreference(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

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

    public EditTextPreference(Context context)
    {
        super(context, null);
    }

    @Override
    protected void onDialogClosed(boolean positiveResult)
    {
        super.onDialogClosed(positiveResult);

        setSummary(getSummary());
    }

    @Override
    public CharSequence getSummary()
    {
        return getText();
    }
}
Trejo answered 19/3, 2016 at 13:42 Comment(0)
C
2

If you are using AndroidX you can use a custom SummaryProvider. This approach can be used for any Preference.

Example from documentation (Java):

EditTextPreference countingPreference = (EditTextPreference) findPreference("counting");

countingPreference.setSummaryProvider(new SummaryProvider<EditTextPreference>() {
    @Override
    public CharSequence provideSummary(EditTextPreference preference) {
        String text = preference.getText();
        if (TextUtils.isEmpty(text)){
            return "Not set";
        }
        return "Length of saved value: " + text.length();
    }
});

Example from documentation (Kotlin):

val countingPreference = findPreference("counting") as EditTextPreference

countingPreference.summaryProvider = SummaryProvider<EditTextPreference> { preference ->
    val text = preference.text
    if (TextUtils.isEmpty(text)) {
        "Not set"
    } else {
        "Length of saved value: " + text.length
    }
}
Caine answered 3/4, 2019 at 12:29 Comment(0)
R
1

To set the summary of a ListPreference to the value selected in a dialog you could use this code:

package yourpackage;

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

public class ListPreference extends android.preference.ListPreference {

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

    protected void onDialogClosed(boolean positiveResult) {
        super.onDialogClosed(positiveResult);
        if (positiveResult) setSummary(getEntry());
    }

    protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
        super.onSetInitialValue(restoreValue, defaultValue);
        setSummary(getEntry());
    }
}

and reference the yourpackage.ListPreference object in your preferences.xml remembering to specify there your android:defaultValue as this triggers the call to onSetInitialValue().

If you want you can then modify the text before calling setSummary() to whatever suits your application.

Rhamnaceous answered 31/1, 2012 at 11:49 Comment(0)
P
1

Because I'm using a custom PreferenceDataStore, I can't add a listener to some SharedPreference so I've had to write a somewhat hacky solution that listens to each preference:

class SettingsFragment : PreferenceFragmentCompat(), Preference.OnPreferenceChangeListener {
    private val handler: Handler by lazy { Handler(Looper.getMainLooper()) }

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        preferenceManager.preferenceDataStore = prefs
        addPreferencesFromResource(R.xml.app_preferences)
        onPreferenceChange(preferenceScreen, null)
    }

    override fun onPreferenceChange(preference: Preference, newValue: Any?): Boolean {
        preference.onPreferenceChangeListener = this

        when (preference) {
            is PreferenceGroup -> for (i in 0 until preference.preferenceCount) {
                onPreferenceChange(preference.getPreference(i), null)
            }
            is ListPreference -> {
                if (preference.value == null) {
                    preference.isPersistent = false
                    preference.value = Preference::class.java.getDeclaredField("mDefaultValue")
                            .apply { isAccessible = true }
                            .get(preference).toString()
                    preference.isPersistent = true
                }

                postPreferenceUpdate(Runnable { preference.summary = preference.entry })
            }
        }
        return true
    }

    /**
     * We can't directly update the preference summary update because [onPreferenceChange]'s result
     * is used to decide whether or not to update the pref value.
     */
    private fun postPreferenceUpdate(r: Runnable) = handler.post(r)
}
Predecessor answered 10/8, 2017 at 20:45 Comment(0)
S
0

Here is a working solution for all EditTextPreferences inside of a PreferenceFragment based on @tdeveaux answer:

public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
    private static final String TAG = "SettingsFragment";

    @Override
    public void onCreate (Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onResume () {
        super.onResume();

        for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
            Preference preference = getPreferenceScreen().getPreference(i);
            updatePreference(preference);
        }
    }

    @Override
    public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
        updatePreference(findPreference(key));
    }

    private void updatePreference (Preference preference) {
        if (preference instanceof EditTextPreference) {
            EditTextPreference editTextPreference = (EditTextPreference)preference;
            editTextPreference.setSummary(editTextPreference.getText());
        }
    }
}
Spumescent answered 5/2, 2017 at 3:59 Comment(1)
you have to unregister listenerDeactivate
D
0

I found this way to make EditTextPreference from support library handle "%s" in summary (as ListPreference already handles):

public class EditTextPreference extends android.support.v7.preference.EditTextPreference {
    public EditTextPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(String text) {
        super.setText(text);
        notifyChanged();
    }

    @Override
    public CharSequence getSummary() {
        String text = super.getText();
        String summary = super.getSummary().toString();
        return String.format(summary, text == null ? "" : text);
    }
}

In xml it will look like this:

<com.example.yourapp.EditTextPreference
    android:defaultValue="1"
    android:key="cleanup_period"
    android:summary="Clean up messages after %s days"
    android:title="Clean up period" />
Deadlight answered 6/5, 2018 at 13:23 Comment(0)
F
0

@tdevaux put the good solution above but it works partially; since I have not only string values in sharedPreferences there were errors:

  • android.content.res.Resources$NotFoundException: String resource ID #0xc83
  • java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

So my changes for the updatePreferences method add switch for different types of Preferences to avoid cast errors:

private void updatePreference(Preference preference, String key) {
if (preference == null) return;
if (preference instanceof ListPreference) {
    ListPreference listPreference = (ListPreference) preference;
    listPreference.setSummary(listPreference.getEntry());
    return;
}
SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();

switch (key) {
    // integer values assignment
    case "prf_points":
    case "prf_hours":
    case "prf_level":
        preference.setSummary("" + sharedPrefs.getInt(key, 0));
        break;

    // String values assignment
    case "prf_user_name":
    case "prf_user_email":
        preference.setSummary(sharedPrefs.getString(key, "-"));
        break;
    default:
        break;
}

}

Fulsome answered 5/11, 2023 at 15:2 Comment(0)
S
-1

The concise solution by 1 line of code:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.preferences);

    bindPreferenceSummaryToValue(findPreference("mySetting"));

    // initialize summary
    sBindPreferenceSummaryToValueListener.onPreferenceChange(findPreference("mySetting"), 
        ((ListPreference) findPreference("mySetting")).getEntry());
}
Steeplejack answered 27/8, 2018 at 10:18 Comment(1)
OK, and what is bindPreferenceSummaryToValue() ? Also, this is not one line of code as yo usay.Gessner
F
-1

Just add this line to your xml specification. app:useSimpleSummaryProvider="true"

For example:

<your.package.name.MyListPreference

android:key="noteInterval"
android:defaultValue="60"
android:title="Notification Interval"
android:entries="@array/noteInterval"
android:entryValues="@array/noteIntervalValues"
app:useSimpleSummaryProvider="true"

/>

Fortuity answered 9/8, 2022 at 10:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.