4fe29fbe8a73b7b87f9870d868385a4c97309c78
[Sunshine.git] / app / src / main / java / uk / me / njae / sunshine / SettingsActivity.java
1 package uk.me.njae.sunshine;
2
3 import android.os.Bundle;
4 import android.preference.ListPreference;
5 import android.preference.Preference;
6 import android.preference.PreferenceActivity;
7 import android.preference.PreferenceManager;
8
9 /**
10 * A {@link PreferenceActivity} that presents a set of application settings.
11 * <p>
12 * See <a href="http://developer.android.com/design/patterns/settings.html">
13 * Android Design: Settings</a> for design guidelines and the <a
14 * href="http://developer.android.com/guide/topics/ui/settings.html">Settings
15 * API Guide</a> for more information on developing a Settings UI.
16 */
17 public class SettingsActivity extends PreferenceActivity
18 implements Preference.OnPreferenceChangeListener {
19
20 @Override
21 public void onCreate(Bundle savedInstanceState) {
22 super.onCreate(savedInstanceState);
23 // Add 'general' preferences, defined in the XML file
24 addPreferencesFromResource(R.xml.pref_general);
25
26 // For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
27 // updated when the preference changes.
28 bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_location_key)));
29 bindPreferenceSummaryToValue(findPreference(getString(R.string.pref_units_key)));
30
31 }
32
33 /**
34 * Attaches a listener so the summary is always updated with the preference value.
35 * Also fires the listener once, to initialize the summary (so it shows up before the value
36 * is changed.)
37 */
38 private void bindPreferenceSummaryToValue(Preference preference) {
39 // Set the listener to watch for value changes.
40 preference.setOnPreferenceChangeListener(this);
41
42 // Trigger the listener immediately with the preference's
43 // current value.
44 onPreferenceChange(preference,
45 PreferenceManager
46 .getDefaultSharedPreferences(preference.getContext())
47 .getString(preference.getKey(), ""));
48 }
49
50 @Override
51 public boolean onPreferenceChange(Preference preference, Object value) {
52 String stringValue = value.toString().trim();
53
54 if (preference instanceof ListPreference) {
55 // For list preferences, look up the correct display value in
56 // the preference's 'entries' list (since they have separate labels/values).
57 ListPreference listPreference = (ListPreference) preference;
58 int prefIndex = listPreference.findIndexOfValue(stringValue);
59 if (prefIndex >= 0) {
60 preference.setSummary(listPreference.getEntries()[prefIndex]);
61 }
62 } else {
63 // For other preferences, set the summary to the value's simple string representation.
64 preference.setSummary(stringValue);
65 }
66 return true;
67 }
68
69 }