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 ?
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();
}
}
}
View view = getLayoutInflater().inflate(R.layout.custom_dialog, null);
EditText editTextEmail=(EditText)view.findViewById(R.id.edittext_email);
AlertDialog alertDialog = new AlertDialog.Builder(YourCurrentActivity.this)
.setView(view)
.setPositiveButton(R.string.lbl_ok, null)
.setNegativeButton(R.string.lbl_cancel, null)
.create();
alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button buttonPositive = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_POSITIVE);
buttonPositive.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Do something when button positive clicked
// Your validation is here
});
Button buttonNegative = ((AlertDialog) dialog).getButton(DialogInterface.BUTTON_NEGATIVE);
buttonNegative.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Do something when button negative clicked
}
});
}
});
alertDialog.show();
来源:https://stackoverflow.com/questions/11363209/alertdialog-with-positive-button-and-validating-custom-edittext