Android prevent a dialog from closing when a button is clicked

  My problem was that when a user clicks the Sign Up for example button I wanted to validate a field if it contains a valid email and after that dismiss or keep the dialog showing.

To achieve that I just copied the code from here which overrides the click of the buttons:

http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked

final AlertDialog d = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();

d.setOnShowListener(new DialogInterface.OnShowListener() {

@Override
public void onShow(DialogInterface dialog) {

Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// TODO Do something

//Dismiss once everything is OK.
d.dismiss();
}
});
}

You may also like...