Android 带有正按钮并验证自定义 EditText 的 AlertDialog

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11363209/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:10:27  来源:igfitidea点击:

AlertDialog with positive button and validating custom EditText

androidandroid-dialog

提问by hsz

I have created simple AlertDialogwith positive and negative buttons. Positive button has registered DialogInterface.OnClickListener, where I get EditTextvalue. 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 ?

我创造了简单AlertDialog的正面和负面按钮。正按钮已注册DialogInterface.OnClickListener,我从中获得EditText价值。我必须验证它(例如,如果它必须不为空),如果值不正确,则不允许关闭此对话框。单击并验证后如何防止关闭对话框?

回答by FoamyGuy

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();
        }
    }
}