android – AlertDialog带正按钮并验证自定义EditText

栏目: IOS · Android · 发布时间: 6年前

内容简介:我创建了简单的AlertDialog,带有正负按钮.正按钮已注册DialogInterface.OnClickListener,在那里我获得EditText值.我必须验证它(例如,如果它不为null),如果值不正确,不允许关闭此对话框.点击后如何防止关闭对话框验证?http://stackoverflow.com/questions/11363209/alertdialog-with-positive-button-and-validating-custom-edittext

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

对话创建:

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

http://stackoverflow.com/questions/11363209/alertdialog-with-positive-button-and-validating-custom-edittext


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Head First 设计模式(中文版)

Head First 设计模式(中文版)

弗里曼 / O'Reilly Taiwan公司 / 中国电力出版社 / 2007-9 / 98.00元

《Head First设计模式》(中文版)共有14章,每章都介绍了几个设计模式,完整地涵盖了四人组版本全部23个设计模式。前言先介绍这本书的用法;第1章到第11章陆续介绍的设计模式为Strategy、Observer、Decorator、Abstract Factory、Factory Method、Singleton,Command、Adapter、Facade、TemplateMethod、I......一起来看看 《Head First 设计模式(中文版)》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换