AlertDialog无法关闭,需要点击两次才能关闭 [英] AlertDialog does not dismiss, takes twice tap to close

查看:689
本文介绍了AlertDialog无法关闭,需要点击两次才能关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大约3周以来,我一直在尝试学习和玩Android Studio.我只是遇到一种情况,即AlertDialogue在单击肯定按钮时不会消失.

I have been trying to learn and play with Android studio for about 3 weeks now. I just came to a situation where AlertDialogue doesn't dismiss on clicking on positive button.

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);
}

好像我必须双击肯定按钮才能结束对话.

It looks like I am only able to close the dialogue if I have to double click on positive.

另一方面,使用否定按钮则没有这种麻烦.我猜,由于否定按钮关闭了整个应用程序,因此可以解决该问题,否则情况将是相同的.

On the other hand, with negative button there is no such trouble. I guess, since negative button shuts down the whole application, and hence that is taking care of that problem else it would have been the same.

推荐答案

您无需通过在对话框界面按钮的onClick方法内调用dialog.dismiss();来显式关闭警报对话框.

You don't need to explicitly dismiss the alert dialog by calling dialog.dismiss(); inside the onClick method of the dialog interface buttons.

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

The dialog will automatically be closed once you click any of those buttons.

如果您在单击按钮后告诉对话框没有消失,则可能已创建了多个对话框,因此即使关闭了一个对话框,仍然存在另一个对话框.

If you're telling the dialog isn't gone after you click the button, you might have created multiple dialogs so that even one dialog is dismissed, another one is still there.

这篇关于AlertDialog无法关闭,需要点击两次才能关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆