带有正按钮和验证自定义 EditText 的 AlertDialog [英] AlertDialog with positive button and validating custom EditText

查看:27
本文介绍了带有正按钮和验证自定义 EditText 的 AlertDialog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了带有正负按钮的简单AlertDialog.肯定按钮已注册 DialogInterface.OnClickListener,在那里我获得 EditText 值.我必须验证它(例如,如果它必须不为空),如果值不正确,则不允许关闭此对话框.单击并验证后如何防止关闭对话框?

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 ?

推荐答案

对话框创建:

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

这篇关于带有正按钮和验证自定义 EditText 的 AlertDialog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆