I have created simple AlertDialog
with positive and negative buttons. Positive button has registered DialogInterface.OnClickListener
, where I get EditText
value. I have to validate it (for example if it has to be not null) and if value is not correct, disallow to close this dialog. How to prevent dismissing dialog after click and validate ?
Asked
Active
Viewed 2.7k times
19

hsz
- 148,279
- 62
- 259
- 315
-
i think you should use `custom dialog with EditText`,and when you click any button of alertDialog it dismiss dialog. – Samir Mangroliya Jul 06 '12 at 13:36
-
You can try this http://stackoverflow.com/questions/14391133/how-to-validate-string-entered-by-user-using-alertdialog – Jan 18 '13 at 02:26
1 Answers
60
Dialog creation:
AlertDialog.Builder builder = new AlertDialog.Builder(YourActivity.this);
builder.setCancelable(false)
.setMessage("Please Enter data")
.setView(edtLayout) //<-- layout containing EditText
.setPositiveButton("Enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//All of the fun happens inside the CustomListener now.
//I had to move it to enable data validation.
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
Button theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(alertDialog));
CustomListener:
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
// put your code here
String mValue = mEdtText.getText().toString();
if(validate(mValue)){
dialog.dismiss();
}else{
Toast.makeText(YourActivity.this, "Invalid data", Toast.LENGTH_SHORT).show();
}
}
}

FoamyGuy
- 46,603
- 18
- 125
- 156
-
2This works for me, but you don't need to go to the extent of creating the CustomListener class. Instead, you can use an anonymous, inline listener. – ban-geoengineering Dec 22 '14 at 13:48
-
1@ban-geoengineering it has been a LONG time since I had to do it so I could be mis-remembering, but I think the issue with the anonymous inline listener was that it forced the dialog to close no matter if the data was valid or not. I wanted the dialog to stay open in the event that the data was not valid. – FoamyGuy Dec 22 '14 at 14:42
-
@FoamyGuy: anonymous listener works OK too (dialog stays opened unless you dismiss it explicitly). Thanks for the solution! – johndodo Aug 24 '16 at 08:01