Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change the background of Android alert dialogs?

I use the AlertDialog class in my application. By default, these alert dialogs have a transparent background. I'm trying to use an opaque background instead, very unsuccessfully. These are my styles:

<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>

I applied the "MyOpaqueActivity" style successfully for whole activities (the window background is changed to "my_background"), but it doesn't work for alert dialogs within those activities. The "alertDialogStyle" attribute and my "MyOpaqueAlertDialog" style don't seem to have any effect.

So how can I change the background of these alert dialogs?

like image 864
Alpha Hydrae Avatar asked Jun 25 '10 14:06

Alpha Hydrae


1 Answers

Your approach won't work. It seems AlertDialog (and Builder) hardcode the theme and don't honor alertDialogStyle anywhere:

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);
}

They came to the same conclusion here.

A custom dialog class derived from AlertDialog that calls the protected constructor AlertDialog(context, R.style.MyOpaqueAlertDialog) would be a workaround.

In the latest android source, there is a new public constructor for AlertDialog.Builder that takes a theme argument. Unfortunately, it hasn't been released yet (maybe in Gingerbread?).

like image 56
kipkennedy Avatar answered Oct 18 '22 22:10

kipkennedy