AlertDialog不会解散,需要两次点击才能关闭

时间:2017-10-24 18:13:47

标签: java android android-alertdialog

我一直在努力学习和玩Android工作室约3周。我刚刚遇到AlertDialogue在点击“正面”按钮时没有解雇的情况。

private void showGPSDisabledAlertToUser() {
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(this);
    }

    builder.setTitle("Turn On Location / GPS");
    builder.setCancelable(false);
    builder.setMessage("Application Needs To Determine Device's Physical Location.");
    builder.setPositiveButton("YES, TURN ON", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss(); // This ain't working
                    goToInternetSettings();
                }
            });
    builder.setNegativeButton("NO, CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    closeApplication();
                }
            });
    builder.create().show();
}

private void goToInternetSettings() {
    Intent gpsSetting = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(gpsSetting);
}

private void closeApplication() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
}

如果我必须双击肯定,我似乎只能关闭对话。

另一方面,使用负按钮没有这样的麻烦。我猜,因为负面按钮关闭了整个应用程序,因此这就解决了这个问题,否则就会一样。

2 个答案:

答案 0 :(得分:1)

您不需要通过在对话框界面按钮的dialog.dismiss();方法中调用onClick来明确关闭警报对话框。

单击任何一个按钮后,对话框将自动关闭。

如果您在单击按钮后告诉对话框没有消失,您可能已经创建了多个对话框,这样即使一个对话框被解除,另一个对话框仍然存在。

答案 1 :(得分:1)

您不需要在dialog.dismiss()内拨打setPositiveButton() OnClickListener,因为它是隐式调用的。

在检查GPS可用性时,您可能多次拨打showGPSDisabledAlertToUser()。您可以尝试创建一次对话框并再次使用以下内容重新显示:

AlertDialog mAlertDialog;

private void showGPSDisabledAlertToUser() {
  // build the alert dialog once.
  if (mAlertDialog == null) {
    AlertDialog.Builder builder;

    ...
    // Do your dialog initialization here.
    ...

    mAlertDialog = builder.create();
  }

   mAlertDialog.show();
}
相关问题