Android 在 hide() 之后显示 AlertDialog()

Android AlertDialog show() after hide()

我在使用 AlertDialog 时遇到了问题。如果我在 dialog.hide() 之后调用 dialog.show() 它将不会显示,但是如果我再次调用 dialog.show(),一切正常。如果我连续调用 dialog.show() 两次,对话框总是显示。

如果替换 hide() -> dismiss() 就没问题。但就我而言,我需要使用 hide() 来保存对话框。

样本

AlertDialog dialog;

@Override
protected void onCreate(@Nullable Bundle savedState) {
    super.onCreate(savedState);
    setContentView(R.layout.activity_auth);
    dialog = new AlertDialog.Builder(this)
        .setTitle("Title")
        .setMessage("Text")
        .setPositiveButton("Yes", (dialogInterface, which) -> onYesClicked())
        .create();
    Button login = findViewById(R.id.btn_login);
    login.setOnClickListener(v -> dialog.show());
}

private void onYesClicked() {
    dialog.hide();
}

已编辑:解决方案

private void onYesClicked() {
    new Handler().post(() -> dialog.hide());
}

如果使用 hide(),可能会导致 Leaked Window 错误。请看:Activity has leaked window that was originally added

使用 dismiss() 并保存 message/title 而不是整个对话框。

如果您想再次使用隐藏和显示对话框,请尝试此代码:

dialog.setOnShowListener(new DialogInterface.OnShowListener() {
    @Override
    public void onShow(DialogInterface d) {
        dialog.show();
    }
});

当你调用 hide 和调用 show 时,回调将被调用。

试试这个让对话框只弹出一次:

 if (dialog != null && dialog.getDialog() != null
                                && dialog.getDialog().isShowing()) {
                     //Leave Empty here or your way
}else{
 code to open a dialog
}

对下面代码中使用的 onYesClicked() 方法进行一些更改..

private void onYesClicked() {
    new Handler().postDelayed(new Runnable() {

        // Showing message with a timer.
        @Override
        public void run() {
            dialog.hide();
        }
    }, 1000);

}

我解决了这个问题。方法 hide() 在单击按钮(由 AlerdDialog.Builder 创建)时调用是无用的。因为系统发送 MSG_DISMISS_DIALOG 并为此对话框自动调用 dismiss():

SDK代码:

        // Post a message so we dismiss after the above handlers are executed
        mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
                .sendToTarget();