Done lesson 3.08
[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 }
30
31 /**
32 * Attaches a listener so the summary is always updated with the preference value.
33 * Also fires the listener once, to initialize the summary (so it shows up before the value
34 * is changed.)
35 */
36 private void bindPreferenceSummaryToValue(Preference preference) {
37 // Set the listener to watch for value changes.
38 preference.setOnPreferenceChangeListener(this);
39
40 // Trigger the listener immediately with the preference's
41 // current value.
42 onPreferenceChange(preference,
43 PreferenceManager
44 .getDefaultSharedPreferences(preference.getContext())
45 .getString(preference.getKey(), ""));
46 }
47
48 @Override
49 public boolean onPreferenceChange(Preference preference, Object value) {
50 String stringValue = value.toString();
51
52 if (preference instanceof ListPreference) {
53 // For list preferences, look up the correct display value in
54 // the preference's 'entries' list (since they have separate labels/values).
55 ListPreference listPreference = (ListPreference) preference;
56 int prefIndex = listPreference.findIndexOfValue(stringValue);
57 if (prefIndex >= 0) {
58 preference.setSummary(listPreference.getEntries()[prefIndex]);
59 }
60 } else {
61 // For other preferences, set the summary to the value's simple string representation.
62 preference.setSummary(stringValue);
63 }
64 return true;
65 }
66
67 }