Finally found a solution by doing the following:
I used a
SharedPreferences.OnSharedPreferenceChangeListener
instead of aPreference.OnPreferenceChangeListener
. ThePreference.OnPreferenceChangeListener
looks for when the user changes a preference through the settings menu, and behaves before the change is committed to the preference data. TheSharedPreferences.OnSharedPreferenceChangeListener
listens for changes to the actual preference data, not changes in the GUI, so it happens a little later. I noticed that in my first attempt, I could runsetText()
immediately followed bygetText()
on myEditTextPreference
object, and thegetText()
value wouldn't match what I had just set thesetText()
value to. I'm not sure why this happens, but waiting for the changes to actually commit before trying to runsetText()
led to the correct response. Maybe it was a timing issue?I run
setPreferenceScreen(null)
andaddPreferencesFromResource(R.xml.settings)
after updating the value in theEditTextPreference
. If I didn't do this, sometimes when the user would click on theEditTextPreference
again, the value in the field would appear blank even though the value in the settings file wasn't. This forces the settings page to, more or less, refresh itself.
The working code is below:
public class SettingsActivity extends PreferenceActivity {
private String oldCatName;
private EditTextPreference catName;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
createListener();
catName = (EditTextPreference) findPreference("cat_name");
oldCatName = catName.getText();
}
private void createListener() {
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(
SharedPreferences sharedPreferences, String key) {
String value = sharedPreferences.getString("cat_name", "NULL");
if (value.equals("")) {
catName.setText(oldCatName);
setPreferenceScreen(null);
addPreferencesFromResource(R.xml.settings);
} else {
oldCatName = value;
}
}
};
PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.registerOnSharedPreferenceChangeListener(listener);
}
}