AlertDialog阳性按钮和验证定制的EditText阳性、按钮、AlertDialog、EditText

由网友(一路上的荆棘)分享简介:我创建了简单的 AlertDialog 有正面和负面的按钮。正面按钮注册 DialogInterface.OnClickListener ,在那里我得到的EditText 值。我要验证它(例如,如果它是不为空),如果值是不正确的,禁止关闭该对话框。如何prevent点击后驳回对话框和验证?解决方案 对话创造:Aler...

我创建了简单的 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();
        }
    }
}
 

对话框AlertDialog的使用

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

阅读全文

相关推荐

最新文章