我创建了带有正面和负面按钮的简单AlertDialog
。正面按钮已注册DialogInterface.OnClickListener
,我获得EditText
值。我必须验证它(例如,如果它必须不为null)并且如果值不正确,则禁止关闭此对话框。单击并验证后如何防止解除对话?
答案 0 :(得分:54)
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));
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();
}
}
}
答案 1 :(得分:0)
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();