Search code examples
androidpreferencessharedpreferences

Android preferences show value and unit


Is it possible to show a preference with the unit (while still only taking the value)

For example:

Having the preference Distance which is a EditTextPreference and the preference Distance Unit which is a ListPreference

So when they are displayed it shows:

Distance
value + unit

Distance Unit
unit

Example:

Distance
5 km
Distance Unit
km

then change distance unit:

Distance
5 mi
Distance Unit
mi

However, all I really care about is the 5, but i still want to show the unit beside it. Is this possible?

Thanks


Solution

  • Sure you can. Just implement a custom onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) for your Distance and your Unit.

    Find your preference with the Distance-key and use setSummary(String summary) to append the unit to the distance.

    Here some fancy code:

    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
       if (key.equals("distance") | key.equals("unit")) {
          findPreference("distance").setSummary(sharedPreferences.getString("distance", "0") + sharedPreferences.getString("unit", "km"));
       }
    }