有没有办法阻止AlertDialog关闭无效输入?

时间:2011-06-28 18:54:47

标签: android alertdialog

我正在使用带有正面和取消按钮的简单文本字段警告对话框。我想验证我的警报对话框,如果输入无效,则阻止完成按钮关闭AlertDialog。

如果验证失败,有没有办法创建自定义对话框以防止PositiveButton onClick()处理程序关闭对话框?

class CreateNewCategoryAlertDialog {
    final EditText editText;
    final AlertDialog alertDialog;

    class PositiveButtonClickListener implements OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            String name = editText.getText().toString();
            if(name.equals("")) {
                editText.requestFocus();
                editText.setError("Please enter a name");
                // Some code to stop AlertDialog from closing goes here...
            } else {
                doSomethingUsefulWithName();
            }
        }
    }

    AlertDialog buildAlertDialog(Context context) {
        return new AlertDialog.Builder(context)
        .setTitle(context.getString(R.string.enter_name))
        .setMessage(context.getString(R.string.enter_name_msg))
        .setView(editText)
        .setPositiveButton(context.getString(R.string.done), new PositiveButtonClickListener())
        .setNegativeButton(context.getString(R.string.cancel), null).create();
    }
}

1 个答案:

答案 0 :(得分:9)

我是这样做的。从技术上讲,它在技术上不会使对话框保持打开状态,它会暂时关闭它并重新打开它,但最终结果是相同的。

class MyAlertDialog implements OnDismissListener, OnCancelListener {
    final private EditText editText;
    final private AlertDialog alertDialog;
    final private EventManager eventManager;
    final private CategorySelector categorySelector;

    private Boolean canceled;

    MyAlertDialog(Context context) {
        editText = new EditText(context);
        alertDialog = buildAlertDialog(context);
        alertDialog.setOnDismissListener(this);
        alertDialog.setOnCancelListener(this);
        show();
    }

    private AlertDialog buildAlertDialog(Context context) {
        return new AlertDialog.Builder(context)
        .setTitle(context.getString(R.string.enter_name))
        .setMessage(context.getString(R.string.enter_name))
        .setView(editText)
        .setNeutralButton(context.getString(R.string.save_text), null)
        .setNegativeButton(context.getString(R.string.cancel_text), null)
            .create();
    }

    public void show() {
        canceled = false;
        alertDialog.show();
    }

    @Override public void onDismiss(DialogInterface dialog) {
        if(!canceled) {
            final String name = editText.getText().toString();
            if(name.equals("")) {
                editText.setError("Please enter a non-empty name");
                show();
            } else {
                doWhateverYouWantHere(name);
            }
        }
    }

    @Override public void onCancel(DialogInterface dialog) {
        canceled = true;
    }
}