我创建了简单AlertDialog
的正面和负面按钮。正面按钮已注册DialogInterface.OnClickListener
,我从中获得EditText
价值。我必须验证它(例如,如果它必须不为空)并且如果值不正确,则不允许关闭此对话框。单击并验证后如何防止关闭对话框?
问问题
26749 次
1 回答
60
对话框创建:
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();
}
}
}
于 2012-07-06T13:49:47.060 回答