如何更改Android警报对话框的背景?

时间:2010-06-25 14:01:12

标签: android dialog background

我在我的应用程序中使用AlertDialog类。默认情况下,这些警报对话框具有透明背景。我试图使用不透明的背景,非常不成功。这些是我的风格:

<style name="MyOpaqueActivity" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@drawable/my_background</item>
    <item name="android:alertDialogStyle">@style/MyOpaqueAlertDialog</item>
</style>

<style name="MyOpaqueAlertDialog" parent="@android:style/Theme.Dialog.Alert">
    <item name="android:background">#454545</item>
    <item name="android:windowBackground">@drawable/my_background</item>
    <item name="android:popupBackground">@drawable/my_background</item>
</style>

我成功地为整个活动应用了“MyOpaqueActivity”样式(窗口背景更改为“my_background”),但它不适用于这些活动中的警报对话框。 “alertDialogStyle”属性和我的“MyOpaqueAlertDialog”样式似乎没有任何效果。

那么如何更改这些警报对话框的背景呢?

3 个答案:

答案 0 :(得分:11)

您的方法无效。似乎AlertDialog(和Builder)对主题进行硬编码,并且不会在任何地方使用alertDialogStyle:

protected AlertDialog(Context context) {
    this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

public Builder(Context context) {
    this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

他们得出了同样的结论here

从AlertDialog派生的自定义对话框类调用受保护的构造函数AlertDialog(context,R.style.MyOpaqueAlertDialog)将是一种解决方法。

在最新的android源代码中,AlertDialog.Builder有一个新的公共构造函数,它接受一个主题参数。不幸的是,它尚未发布(可能是姜饼?)。

答案 1 :(得分:4)

一旦你认为AlertDialogs有一些特殊属性,就很容易以XML风格完成。

然而,了解您所指的(或针对的)哪个Android版本会很有趣。据我所知,Theme.Dialog相对较新。较新的Android版本在旧版本使用它们的所有情况下也不使用AlertDialog。

这适用于Android 2.2:

<style name="MyTheme" parent="@android:style/Theme">
    <item name="android:alertDialogStyle">@style/MyOpaqueAlertDialog</item>
</style>

<style name="MyOpaqueAlertDialog">
    <item name="android:fullDark">@drawable/[...]</item>
    <item name="android:topDark">@drawable/[...]</item>
    <item name="android:centerDark">@drawable/[...]</item>
    <item name="android:bottomDark">@drawable/[...]</item>
    <item name="android:fullBright">@drawable/[...]</item>
    <item name="android:topBright">@drawable/[...]</item>
    <item name="android:centerBright">@drawable/[...]</item>
    <item name="android:bottomBright">@drawable/[...]</item>
    <item name="android:bottomMedium">@drawable/[...]</item>
    <item name="android:centerMedium">@drawable/[...]</item>
</style>

较新的Android版本还具有针对AlertDialog样式的android:progressLayout和android:horizo​​ntalProgressLayout属性。

此外,在较新的Android版本中,可以通过在自定义主题中使用alertDialogTheme而不是alertDialogStyle来引用AlertDialog主题。 AlertDDialogThemes支持更熟悉和更强大的属性,如windowBackground,windowTitleStyle等。看看styles.xml和themes.xml。

不幸的是,当超级差时添加了哪些功能的文档。请自行了解哪种方法最适合您。

答案 2 :(得分:3)

documentation来看,你可以在onCreateDialog中执行此操作。

FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom);
fl.setBackgroundResource(); // has to be a drawable.

只有其他解决方案才是使用该主题的自定义对话框。