Android PreferenceScreen - Can I use it without saving preferences to SharedPreferences?
I know that's an old question but I find it quite interesting. Just set this attribute to your preference and it won't be saved:
android:persistent="false"
I re-read the appropriate docs and determined how to prevent saving preferences by implementing the Preference.OnPreferenceChangeListener
interface.
public static interface Preference.OnPreferenceChangeListener
Interface definition for a callback to be invoked when the value of this Preference has been changed by the user and is about to be set and/or persisted. This gives the client a chance to prevent setting and/or persisting the value.
Example:
public class SettingsFragment extends PreferenceFragment {
public static SettingsFragment newInstance(int index) {
SettingsFragment f = new SettingsFragment();
Bundle args = new Bundle();
args.putInt("index", index);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.settings);
// getArguments().getInt("index");
EditTextPreference namePreference = (EditTextPreference) findPreference("settings_edit_name");
namePreference.setOnPreferenceChangeListener(new NamePreferenceChangeListener());
}
private class NamePreferenceChangeListener implements Preference.OnPreferenceChangeListener {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Do something else presumably and then return false to avoid saving the pref.
return false;
}
}