Last active
August 29, 2015 14:12
-
-
Save silmood/8994f78e62204c7d8e68 to your computer and use it in GitHub Desktop.
SettingsFragment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class SettingsFragment extends PreferenceFragment | |
| implements Preference.OnPreferenceChangeListener{ | |
| public static SettingsFragment newInstance() { | |
| SettingsFragment fragment = new SettingsFragment(); | |
| Bundle args = new Bundle(); | |
| fragment.setArguments(args); | |
| return fragment; | |
| } | |
| public SettingsFragment() { | |
| // Required empty public constructor | |
| } | |
| @Override | |
| public void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| } | |
| /** | |
| * Attaches a listener so the summary is always updated with the preference value. | |
| * Also fires the listener once, to initialize the summary (so it shows up before the value | |
| * is changed.) | |
| */ | |
| private void bindPreferenceSummaryToValue(Preference preference) { | |
| // Set the listener to watch for value changes. | |
| preference.setOnPreferenceChangeListener(this); | |
| // Trigger the listener immediately with the preference's | |
| // current value. | |
| onPreferenceChange(preference, | |
| PreferenceManager | |
| .getDefaultSharedPreferences(preference.getContext()) | |
| .getString(preference.getKey(), "")); | |
| } | |
| @Override | |
| public boolean onPreferenceChange(Preference preference, Object value) { | |
| String stringValue = value.toString(); | |
| if (preference instanceof ListPreference) { | |
| // For list preferences, look up the correct display value in | |
| // the preference's 'entries' list (since they have separate labels/values). | |
| ListPreference listPreference = (ListPreference) preference; | |
| int prefIndex = listPreference.findIndexOfValue(stringValue); | |
| if (prefIndex >= 0) { | |
| preference.setSummary(listPreference.getEntries()[prefIndex]); | |
| } | |
| } else { | |
| // For other preferences, set the summary to the value's simple string representation. | |
| preference.setSummary(stringValue); | |
| } | |
| return true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The app crashes one I hit the settings