Does anyone have sample code to validate user entered text in preferences? For example, I have a EditTextPreference for user to enter an email address. I'd like to validate the format of email address entered and pop up an alert dialog if the format isn't correct. Anyone have any sample code for this? Thanks
Implement Preference.OnPreferenceChangeListener
boolean onPreferenceChange(Preference preference, Object newValue)
Called when a Preference has been changed by the user. This is called before the state of the Preference is about to be updated and before the state is persisted.
Returns True to update the state of the Preference with the new value.
So you can directly return the result of value validation.
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
findPreference("mail_preference_key").setOnPreferenceChangeListener(
new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
return Pattern.matches("mailPattern", (String) newValue);
}
});
}
}