github:
* The below material is from Udacity Nanodegree Program- Become an Android Developer *
Setting an acceptable range
To limit the acceptable values between 0 (non inclusive) and 3 (inclusive) we opted to use a PreferenceChangeListener – this is not the same as a SharedPreferenceChangeListener. The differences are:
- SharedPreferenceChangeListener is triggered after any value is saved to the SharedPreferences file.
- PreferenceChangeListener is triggered before a value is saved to the SharedPreferences file. Because of this, it can prevent an invalid update to a preference. PreferenceChangeListeners are also attached to a single preference.
Generally the flow goes like this:
- User updates a preference.
- PreferenceChangeListener triggered for that preference.
- The new value is saved to the SharedPreference file.
- onSharedPreferenceChanged listeners are triggered.
Otherwise they act very similarly. In your activity you implement the Preference.OnPreferenceChangeListener, override the onPreferenceChange(Preference preference, Object newValue). The onPreferenceChange method will return either true or false, depending on whether the preference should actually be saved.
// TODO (1) Implement OnPreferenceChangeListener public class SettingsFragment extends PreferenceFragmentCompat implements OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener {
// TODO (2) Override onPreferenceChange. This method should try to convert the new preference value // to a float; if it cannot, show a helpful error message and return false. If it can be converted // to a float check that that float is between 0 (exclusive) and 3 (inclusive). If it isn't, show // an error message and return false. If it is a valid number, return true. // using the onPreferenceChange listener for checking whether the size setting was set to a valid value. @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Toast errorInput = Toast.makeText(getContext(), "Please enter a number between 0.1 and 3.", Toast.LENGTH_LONG); String sizeKey = getString(R.string.pref_size_key); // Double check that the preference is the size preference if(preference.getKey().equals(sizeKey)){ try{ float size = Float.parseFloat((String)newValue); if (size > 3 || size <=0 ){ errorInput.show(); return false;} }catch (NumberFormatException nfe){ errorInput.show(); return false; } } return true; }
app/java/SettingsFragment – onCreatePreferences
// TODO (3) Add the OnPreferenceChangeListener specifically to the EditTextPreference Preference preference = findPreference(getString(R.string.pref_size_key)); preference.setOnPreferenceChangeListener(this);