I am trying to add empty field validations on EditText
on AlertDialog
. But even after field is empty error message is not getting displayed, instea
This answer is compiled from Android Dialog, keep dialog open when button is pressed.
As written in Dismissing Dialog API Guide,
When the user touches any of the action buttons created with an AlertDialog.Builder, the system dismisses the dialog for you.
So you need to make a custom click listener for prevent the dialog being closed.
First Way
You can prevent the positive button from closing the dialog. You basically need to:
onClickListener
So, create a listener class:
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
// Do whatever you want here
// If you want to close the dialog, uncomment the line below
//dialog.dismiss();
}
}
Then when showing the dialog use:
AlertDialog dialog = dialogBuilder.create();
dialog.show();
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));
Remember, you need to show the dialog otherwise the button will not be findable. Also, be sure to change DialogInterface.BUTTON_POSITIVE to whatever value you used to add the button. Also note that when adding the buttons in the DialogBuilder
you will need to provide onClickListeners
- you can not add the custom listener in there, though - the dialog will still dismiss if you do not override the listeners after show()
is called.
Second Way
Here is an example of the same approach using an anonymous class instead so it is all in one stream of code:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Test for preventing dialog close");
AlertDialog dialog = builder.create();
dialog.show();
//Overriding the handler immediately after show is probably a better approach than OnShowListener as described below
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean wantToCloseDialog = false;
//Do stuff, possibly set wantToCloseDialog to true then...
if(wantToCloseDialog)
dismiss();
//else dialog stays open. Make sure you have an obvious way to close the dialog especially if you set cancellable to false.
}
});