This is kludge-y, but I've managed to get it working for me. The way you do this, show validation errors on an alert dialog (and prevent the dialog from being dismissed) is to override the OnClickListener
for the dialog button. You may be thinking "I'm already doing that... thanks jerk", but that's the trick. You're probably calling AlertDialog.Builder().setTitle().setView().setPositiveButton(title, new OnClickListener() {...validation logic...}).create();
and then returning that. If you want to prevent the dialog from being dismissed, you need to add an OnShowListener
to the dialog(after it's been created) and override the button click there. Here's an example:
Way that doesn't work:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Dialog example").setPositiveButton(android.R.string.ok, new Dialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// do some validation logic
if (!valid) {
myEditText.setError(R.string.invalid_value); //
} else {
dialog.dismiss();
}
}
});
Dialog dialog = builder.create();
// show the dialog, or return it, whatever you're going to do with it
So the above doesn't work because your onClickListener
is called before the default one is, which will dismiss the dialog. Here's one way around it:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Dialog example").setPositiveButton(android.R.string.ok, null);
Dialog dialog = builder.create();
dialog.setOnShowListener(new OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
((AlertDialog)dialog).getButton(DialogInterface.BUTTON_POSITIVE).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// do some validation logic
if (!valid) {
myEditText.setError(R.string.invalid_value); //
} else {
dialog.dismiss();
}
}
}
});
Just remember, you're responsible for dismissing it!