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).
Here is my solution... FWIW
My option is to extend ListPreference and it's clean:
Then you add in your settings.xml:
I've seen all voted answers show how to set the summary with the exact current value, but the OP wanted also something like:
Here is my answer for achieving that
As documentation says about
ListPreference.getSummary()
:However, I tried 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 overridegetSummary()
to work as specified by Android documentation.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"):
You have to use bindPreferenceSummaryToValue function on the onCreate method.
Example:
See lesson 3 on Udacity Android Course: https://www.udacity.com/course/viewer#!/c-ud853/l-1474559101/e-1643578599/m-1643578601
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:This is easily extensible to other preference classes.
And by using the
getPreferenceCount
andgetPreference
functionality inPreferenceScreen
andPreferenceCategory
, you could easily write a generic function to walk the preference tree setting the summaries of all preferences of the types you desire to theirtoString
representation