AlertDialog阳性按钮和验证定制的EditText [英] AlertDialog with positive button and validating custom EditText

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

问题描述

我创建了简单的 AlertDialog 有正面和负面的按钮。正面按钮注册 DialogInterface.OnClickListener ,在那里我得到的EditText 值。我要验证它(例如,如果它是不为空),如果值是不正确的,禁止关闭该对话框。如何prevent点击后驳回对话框和验证?

解决方案

对话创造:

  AlertDialog.Builder建设者=新AlertDialog.Builder(YourActivity.this);
builder.setCancelable(假)
.setMessage(请输入数据)
.setView(edtLayout)//<  - 包含的EditText布局
.setPositiveButton(回车,新DialogInterface.OnClickListener(){
    公共无效的onClick(DialogInterface对话框,INT ID){
        //所有的乐趣发生在CustomListener里面了。
        //我只好把它移到启用数据验证。
    }
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
按钮theButton = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(新CustomListener(alertDialog));
 

CustomListener:

 类CustomListener实现View.OnClickListener {
    私人最终对话框对话框;
    公共CustomListener(对话对话框){
        this.dialog =对话框;
    }
    @覆盖
    公共无效的onClick(视图v){
        //把你的code在这里
        。字符串mValue = mEdtText.getText()的toString();
        如果(确认(mValue)){
            dialog.dismiss();
        }其他{
            Toast.makeText(YourActivity.this,无效数据,Toast.LENGTH_SHORT).show();
        }
    }
}
 

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

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

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