Android:基于 API,AlertDialog 背景显示不同

Android: AlertDialog background appears different based on API

我刚刚注意到我在 Galaxy S8+(API 24) 上创建和测试的 AlertDialogs 在 Galaxy Note 4(API 19) 上测试时显示不同。我为对话框创建了一个自定义样式,它看起来像在较旧的 API 上,同时显示默认警报对话框和自定义主题。

以下是展示这一点的图片。

S8+ 上的对话框按预期出现

Note 4 的对话框有我的自定义背景和默认背景

这是我的风格和 AlertDialog 代码

AlertDialog 样式

<style name="MyDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">#0053f9</item>
        <item name="android:textColor">#000000</item>
        <item name="android:windowBackground">@drawable/background_color_blue_black_border</item>
        <item name="buttonBarStyle">@style/Widget.AppCompat.ButtonBar</item>
        <item name="buttonBarButtonStyle">@style/customButtonForMyDialogTheme</item>
    </style>

AlertDialog 代码

android.app.AlertDialog.Builder a_builder = new android.app.AlertDialog.Builder(RemoteControlBubblePillar.this, R.style.MyDialogTheme);
            a_builder.setMessage("Do you want to turn on the Bubble Pillar ?")
                    .setCancelable(false)
                    .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            //Do some stuff
                        }
                    })
                    .setNegativeButton("No",new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
            android.app.AlertDialog alert = a_builder.create();
            alert.setTitle("Bubble Pillar Is Turned Off");
            alert.show();

我尝试将背景样式设置为透明,并在代码中将其设置为透明,但目前没有任何效果。知道为什么会这样吗?

这是预期的行为,因为您正在使用基于 API 的 AlertDialog。您可以尝试使用 android.support.v7.app.AlertDialog 而不是 android.app.AlertDialog。或者使用自定义警报对话框库,如 Material Dialogs

使用

android.support.v7.app.AlertDialog

而不是

android.app.AlertDialog

在对话框中设置您的自定义视图。下面是一个示例。

   AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.custom_dialog, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Custom dialog");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //do something with edt.getText().toString();
    }
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        //pass
    }
});
AlertDialog b = dialogBuilder.create();
b.show();