【问题标题】:Android AlerDialog is showing already?Android 警报对话框已经显示?
【发布时间】:2015-03-27 08:41:52
【问题描述】:

如果AlertDialog 已经显示,我该如何阻止它显示?我到处搜索并使用不同的解决方案来为我的项目工作,但是我有一个循环,每 5 秒运行一次并调用 AlertDialog 方法(showSettingsAlert()),每次新的 AlertDialog 堆栈在前一个上.

我希望该方法在开始时检查它是否已显示对话框。

这是我的代码:

public AlertDialog Dialog;
public void showSettingsAlert() {
  if (Dialog != null && Dialog.isShowing()) {
    return;
  } else {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("GPS Disabled");

    alertDialog.setMessage("Do you want to go to location settings menu?");

    alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
      }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });
    Dialog = alertDialog.create();
    Dialog.show();
  }
}

【问题讨论】:

  • 告诉我投反对票的原因,这样我才能真正改进我未来的问题。

标签: android dialog alert


【解决方案1】:

这样做,

//check dialog open method
public boolean checkDialogOpen()
    {
        if (Dialog!= null && Dialog.isShowing())
            return true;
        else
            return false;
    }

您的更新代码,

public AlertDialog Dialog;

public void showSettingsAlert() {

  if (checkDialogOpen()) 
    return;

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
    alertDialog.setTitle("GPS Disabled");

    alertDialog.setMessage("Do you want to go to location settings menu?");

    alertDialog.setPositiveButton("Location Settings", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
      }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

      @
      Override
      public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
      }
    });
    Dialog = alertDialog.create();
    Dialog.show();
  }
}

【讨论】:

  • 你的意思是Dialog,而不是alertDialogcheckDialogOpen 方法中,否则无法解决。
  • 它说不能从静态上下文中引用非静态字段“对话”。我删除了静态并运行了应用程序,但对话框仍在堆叠。
  • 对不起@SnowTauren 请从方法中删除静态。
  • 它通过初始化静态Dialog来工作,我现在唯一的问题是Dialog每5秒显示一次(也许我可以为它做一个触发器)但它不会堆叠(它是我的问题)。将您的帖子标记为答案:)。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-08
相关资源
最近更新 更多