Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: support %s expansion in DialogPreference summary

first question. long time searcher.

i implemented a timePicker preference through expansion of DialogPreference as in the android docs. all works well and i can set the summary through onSharedPreferenceChanged() and also in the override of DialogPreference onSetInitialValue().

my goal is to always have the summary shown with its value and some other strings from resources.
for instance in my ListPreference i have:

android:summary="@string/pref_list_camera_summary"

which resolves to:

<string name="pref_list_camera_summary">Use camera: %s</string>

in my timePreference %s doesn't get expanded. i've searched around and i can't figure out how to get the dialogPreference/timePreference to do this. i can set the summary manually in onSetInitalValue() like this:

setSummary(getSummary() + " " + DateFormat.getTimeFormat(getContext()).format(new Date(calendar.getTimeInMillis())));

i just don't like implied expansion like that. doesn't feel as clean or use the android %s paradigm.

i'll start digging through the listPreference code and see how i can add this to dialogPreference. any ideas/head-starts would be great!

thanks!

like image 627
er0ck Avatar asked Mar 15 '14 16:03

er0ck


2 Answers

If you want to replace the preferred string with %s defined in android:summary automatically, I think there is no such possibility. You should handle it programmatically in initialization of your preference. Have you tried to use String.format() to avoid + concatenation?

String date = DateFormat.getTimeFormat(getContext())
        .format(new Date(calendar.getTimeInMillis()));

setSummary(String.format(Locale.getDefault(), 
        getContext().getString(R.string.pref_list_camera_summary), date));
like image 132
aminography Avatar answered Sep 30 '22 18:09

aminography


If you use library Material Preference, you can do it easily:

listPreference.summaryFormatter = { entry, value -> "Value for $entry is $value" }

It will set your ListPreference's summary to something like Value for Weekly is 7.

I know that this answer is not strongly related to your question. But at least, you have found a library that can do it. With Material Preference, you don't have to set %s to the ListPreference's summary.

like image 28
Anggrayudi H Avatar answered Sep 30 '22 16:09

Anggrayudi H