如何在没有按钮的 onClick 方法的情况下关闭 AlertDialog.Builder?

How to dismiss AlertDialog.Builder without onClick methods of buttons?

我有这两种方法来创建和销毁只有进度条的 AlertDialog。

public static AlertDialog.Builder showProgressAlertDialog(Context context, String title){
    AlertDialog.Builder builder;
    builder = new AlertDialog.Builder(context, R.style.AlertDialogTheme);
    builder.setTitle(title);
    ProgressBar progressBar = new ProgressBar(context);
    builder.setView(progressBar);
    builder.show();
    return builder;
}

public static void dismissProgressAlertDialog(AlertDialog.Builder builder){
    builder.show().cancel();
}

创建时没有错误。但是,当我调用 dismiss 方法时,应用程序抛出以下异常:java.lang.IllegalStateException:指定的 child 已经有一个 parent。您必须先在 child 的 parent 上调用 removeView()。

请注意,我需要调用此方法并从另一个 class 销毁对话框,因此 onClick 方法对我不起作用。

在 AlertDialog 的实例变量上使用 Dismiss()

private AlertDialog dialog;

onCreate() {
    dialog = createAlertDialog(context, title);
}

public static AlertDialog createAlertDialog(Context context, String title){
    final AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.AlertDialogTheme);
    builder.setTitle(title);
    ProgressBar progressBar = new ProgressBar(context);
    builder.setView(progressBar);
    return builder.create();
}

public static void dismissAlertDialog() {
    dialog.dismiss();
}

您应该在 Class 中通过全局 Field 存储 AlertDialog 的实例,现在您可以访问所有 class 中的 AlertDialog 对象

private AlertDialog alertDialog;

public void onCreate(){
  this.alertDialog = new AlertDialog.Builder(context, R.style.AlertDialogTheme)
.create();
}

public void show(){
 this.alertDialog.show()
}

public void close(){
 this.alertDialog.dismiss()
}