Differences between PreferenceChangeListener and SharedPreferenceChangeListener

PreferenceChangeListener 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.

Step 1: Implement the OnPreferenceChangeListener:
public class SettingsFragment extends PreferenceFragmentCompat implements OnSharedPreferenceChangeListener, Preference.OnPreferenceChangeListener
Step 2: Attach the listener to the size preference in onCreatePreferences
@Override
public void onCreatePreferences(Bundle bundle, String s) {
         /* Other preference setup code code */
        //...
        Preference preference = findPreference(getString(R.string.pref_size_key));
        preference.setOnPreferenceChangeListener(this);
}
Step 3: Implement onPreferenceChange
This code will first try to convert the preference into a number and then checks that the number is between 0 and 3. If either of these fail, a toast will be show and false is returned. By returning false, the incorrect value is not saved to shared preferences.
public boolean onPreferenceChange(Preference preference, Object newValue) {
   Toast error = Toast.makeText(getContext(), "Please select a number between 0.1 and 3", Toast.LENGTH_SHORT);

   String sizeKey = getString(R.string.pref_size_key);
   if (preference.getKey().equals(sizeKey)) {
       String stringSize = ((String) (newValue)).trim();
       if (stringSize == null) stringSize = "1";
       try {
           float size = Float.parseFloat(stringSize);
           if (size > 3 || size <= 0) {
               error.show();
               return false;
           }
       } catch (NumberFormatException nfe) {
           error.show();
           return false;
       }
   }
   return true;
}

Bu blogdaki popüler yayınlar

SDLC - Software Development Life Cycle

@SerializedName and @Expose annotations