首页 > 解决方案 > 通过点击三星设备上的背景不会关闭 AlertDialog

问题描述

AlertDialog在我开发的用于显示项目菜单的应用程序中使用(完全披露:使用 React Native,但这是使用本机代码并通过本机模块 API 桥接,因此我认为 RN 不会导致问题)在所有情况下都完美。我使用 Pixel 2 模拟器(API 28,Android 9)开发了它。但是,在三星设备(Galaxy S4、Android 5)上进行测试时,无法通过触摸应用程序背景来关闭对话框;我只能在按下后退按钮时取消它。这是我正在使用的代码:

@ReactMethod
public void showDialog(ReadableArray labelsReadableArray, final Promise promise) {
    final String[] labels = getLabels(labelsReadableArray);
    new AlertDialog.Builder(getCurrentActivity())
        .setItems(labels, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int itemIndex) {
                dialog.dismiss();
                promise.resolve(itemIndex);
            }
        })
        .setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                promise.reject("dialog was closed");
            }
        }).setCancelable(true)
        .show();
}

在我调用的 React Native 代码中:

NativeModules.AndroidPicker.showDialog(labels)
  .then((index) => /* JS/redux action to process the change)
  .catch(err => console.log(err))

为什么三星设备在点击背景时不取消对话框,而其他安卓手机会?我怎样才能解决这个问题?

标签: androidreact-nativeandroid-alertdialog

解决方案


您可以使用以下解决方案AlertDialog通过点击三星设备上的背景来关闭:

AlertDialog alertDialog;
  alertDialog = new AlertDialog.Builder(this).create();
  alertDialog.setCanceledOnTouchOutside(true);

推荐阅读