Sunday, February 7, 2016

Android DialogPreference validation

I've created a custom DialogPreference for one of my apps, but the problem was, I needed to validate the supplied input. I didn't want the dialog to close when the OK button was clicked, if the input was not correct.

To do it, I did as follows, in my custom DialogPreference

@Override
protected void showDialog(Bundle state) {
    super.showDialog(state);
    final AlertDialog dialog = (AlertDialog) getDialog();
    Button button = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
    button.setOnClickListener(new View.OnClickListener() {
         @Override         
         public void onClick(View view) {
             // Validation
             if (mNameEditText.getText().toString().isEmpty()) {
                 mNameEditText.setError(getContext().getString(R.string.pref_error_empty));
                 return;
             }
             PersonPreference.super.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
             dialog.dismiss();
         }
     }
    );
}