android - AlertDialog 在彼此之上显示多个对话框?

标签 android dialog gps android-alertdialog

我的 GPSTracker 中有这个方法:

public void showSettingsAlert() {
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(myContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS Settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // Setting Icon to Dialog
    // alertDialog.setIcon(R.drawable.delete);

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            myContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    alertDialog.show();
}

当我运行它时,我总是同时出现 10 个对话框,所以基本上我可以按 10 次取消或类似的按钮,我该如何解决? 我读过

final AlertDialog alert = alertDialog.create();
if(alert.isShowing()) {
alert.dismiss();
}
else {
alert.show();
}

但这对我不起作用,我仍然在彼此之间进行多次对话...有人可以帮我吗?基本上我打电话 if(gps.isEnabled()) gps.showSettingsAlert();在我的 Activity 上。

if (itemsArrayList.get(position).getCoordinates() == null || !gps.canGetLocation()) {
            holder.distance.setText("Distance not available");
            gps.showSettingsAlert();
        }

最佳答案

我认为 Phan Văn Linh 提供的解决方案是关键,只需要进行一些小的修改。

  • 首先,将 alertDialog 作为您的 Activity 或应用程序(取决于您)的全局变量并将其初始化为 null。

    private AlertDialog.Builder _alertDialog = null;

null 初始化将帮助您检查是否创建了 alertDialog 实例。

  • 然后像这样制作 showSettingDialgo:

    public void showSettingsAlert() { if( _alertDialog != null){//这里我们检查一个实例是否显示 返回;

    _alertDialog = new AlertDialog.Builder(myContext); //设置对话框标题 ... _alertDialog.show();

  • 最后,当对话框关闭时,再次使实例为空。

    _alertDialog = null;

关于android - AlertDialog 在彼此之上显示多个对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37127499/

相关文章:

在对话框外扩展的对话框中的 css 下拉列表

ios - 在iOS中获取GPS卫星和原子钟时间戳

dialog - 如何更改 cq :inplaceEditing 的持久性属性

android - 如何像普通应用程序一样在动态壁纸 Android 中添加应用程序图标

java - 使用 EventKey 在 EditText 上设置文本

android - 清除所有 Activity 的 Glide 缓存?

android - 主题不适用于 Android 上的 DialogFragment

GPS位置修正

iOS 后台应用程序 : best way to run app

android - ActionBar 中的 Spinner 没有出现