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
Your question was an early google hit when I was trying to do the same thing, so hopefully this helps someone. Here's something I hacked together today that demonstrates OnPreferenceChangeListener, thus allowing you to stop invalid changes.
in your fragment:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
Your_Pref = (EditTextPreference) getPreferenceScreen().findPreference("Your_Pref");
Your_Pref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
Boolean rtnval = true;
if (Your_Test) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Invalid Input");
builder.setMessage("Something's gone wrong...");
builder.setPositiveButton(android.R.string.ok, null);
builder.show();
rtnval = false;
}
return rtnval;
}
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With