Edit Text Preference Constraints

github: T06.10- EditTextPreferenceConstraints

Here are the steps: (From Udacity course material)

  1. User updates a preference.
  2. PreferenceChangeListener triggered for that preference.
  3. The new value is saved to the SharedPreference file.
  4. onSharedPreferenceChanged listeners are triggered.

// 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);

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s