我发现所有现有答案的一个问题是没有保留边距。这是因为它们都用纯色覆盖了负责边距的android:windowBackground 属性。但是,我在 Android SDK 中进行了一些挖掘,发现默认的窗口背景可绘制,并对其进行了一些修改以允许透明对话框。
首先,将 /platforms/android-22/data/res/drawable/dialog_background_material.xml 复制到您的项目中。或者,只需将这些行复制到一个新文件中:
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:inset="16dp">
<shape android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="?attr/colorBackground" />
</shape>
</inset>
请注意,android:color 设置为 ?attr/colorBackground。这是您看到的默认纯灰色/白色。要让自定义样式中android:background 中定义的颜色透明并显示透明度,我们只需将?attr/colorBackground 更改为@android:color/transparent。现在它看起来像这样:
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:inset="16dp">
<shape android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="@android:color/transparent" />
</shape>
</inset>
之后,转到您的主题并添加以下内容:
<style name="MyTransparentDialog" parent="@android:style/Theme.Material.Dialog">
<item name="android:windowBackground">@drawable/newly_created_background_name</item>
<item name="android:background">@color/some_transparent_color</item>
</style>
确保将newly_created_background_name 替换为您刚刚创建的可绘制文件的实际名称,并将some_transparent_color 替换为所需的透明背景。
之后,我们需要做的就是设置主题。在创建AlertDialog.Builder 时使用它:
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyTransparentDialog);
然后像往常一样构建、创建和显示对话框!