【问题标题】:AlertDialog with positive button and validating custom EditText带有肯定按钮并验证自定义 EditText 的 AlertDialog
【发布时间】:2012-07-06 23:19:34
【问题描述】:

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

【问题讨论】:

标签: android android-dialog


【解决方案1】:

对话框创建:

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

【讨论】:

  • 这对我有用,但您不需要到创建 CustomListener 类的程度。相反,您可以使用匿名的内联侦听器。
  • @ban-geoengineering 我已经很久没有这样做了,所以我可能记错了,但我认为匿名内联侦听器的问题在于它迫使对话框关闭无论数据是否有效。我希望对话框在数据无效时保持打开状态。
  • @FoamyGuy:匿名侦听器也可以正常工作(除非您明确将其关闭,否则对话框将保持打开状态)。感谢您的解决方案!
猜你喜欢
  • 2018-04-19
  • 2022-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多