从其按钮的回调中解除AlertDialog

时间:2017-04-12 14:21:32

标签: android

我希望能够从其自己的按钮回调中动态关闭AlertDialog

    final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            if (/* if some condition is met */) {
                // dismiss the alert
            } else {
                // keep the alert open
            }
        }
    });
    final AlertDialog alert_dialog = alert.create();
    alert_dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_TOAST);
    alert_dialog.setCanceledOnTouchOutside(false);
    alert_dialog.show();

我知道我可以在dismiss()上拨打alert_dialog,但我不能将此调用放在创建它的代码中。

1 个答案:

答案 0 :(得分:2)

回调中的DialogInterfaceDialog本身(Dialog实现DialogInterface),所以您只需调用DialogInterface#dismiss()方法:

alert.setNeutralButton(R.string.enter, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        if (/* if some condition is met */) {
            dialog.dismiss(); // dismiss the alert
        } else {
            // keep the alert open
        }
    }
});