Custom Transparent Dialog (windowBackground non-ex

2019-07-06 22:25发布

I'm attempting to create a custom dialog with a semi transparent background. I managed to get it to work through code with:

getWindow().setBackgroundDrawableResource(R.color.bg_tran);

Where bg_tran == #A0000000. However I'd rather have it in XML as I use this for several different custom dialog classes. Using just android:background does not work. Nor setting the theme to @android:style/Theme.Translucent worked.

I found several articles talking about using the attribute android:windowBackground. However the android:windowBackground attribute does not exist. Meaning eclipse doesn't show me it as an option for auto complete. I've checked within my style sheet and my actual layout.xml. Since I'm compiling for 2.2 I thought that the issue and changed build target to 4.0.3. No fix. I've even tried explicitly using it anyway but it doesn't work. I searched the Android Dev website and can't even find the page which describes this attribute. Aside from occasionally mentioning in passing, there's nothing. Also looking up setBackgroundDrawableResource doesn't tell me what the equivalent XML attribute tag is. I'm incredibly confused. What am I missing?

Stack overflow references I used to learn above:
Transparent Dialog Theme
Android Dialog Transparent
How to make a custom dialog transparent

Update:
In case it wasn't clear, yes I've tried setting this up within a theme. Does not work. Here's my defined theme:

<style name="my_dialog_theme" parent="@android:style/Theme.Dialog">
    <item name="android:windowBackground">@color/bg_tran</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_width">wrap_content</item>
</style>

2条回答
Lonely孤独者°
2楼-- · 2019-07-06 22:45

You need to define a custom theme for your dialog.

<style name="Theme.CustomDialog" parent="android:Theme.Dialog">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    ...
    ...
</style>

Update:

You can achieve what you want in your dialog by extending the Dialog class. Set the window background drawable in this derived class.

public class CustomDialog extends Dialog 
{
    public CustomDialog (final Context context)
    {
        super(context);

        // This is the layout XML file that describes your Dialog layout
        this.setContentView(R.layout.myDialogLayout);  
        getWindow().setBackgroundDrawableResource(R.color.bg_tran);
    }
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-07-06 22:54

I've experienced the same issue. android:windowBackground attribute just does not appear.you have to type the attribute complete and correct yourself then build your project. Voila, it will compile without any errors and it will work perfectly.

查看更多
登录 后发表回答