How to set dialog window background to transparent, without affecting its margin

Try to below Theme:

<style name="TransaparantDialog">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowFrame">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:background">@android:color/transparent</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

Try below code to apply Theme to AlertDialog.Builder:

final AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(activity, R.style.TransaparantDialog));
...
dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);

I hope help you !


There's a pretty easy way to do that:

You need to "modify" the Drawable that is being used as a background of the Dialog. Those sort of Dialogs use an InsetDrawable as a background.

API >= 23

Only SDK API 23+ allows you to get the source Drawable wrapped by the InsetDrawable (getDrawable() method). With this, you can do whatever you want - e.g. change color to something completely different (like RED or something). If you use this approach remember that the wrapped Drawable is a GradientDrawable and not a ColorDrawable!

API < 23

For lower APIs your ("elegant") options are very limited.

Fortunately you don't need to change the color to some crazy value, you just need to change it to TRANSPARENT. For this you can use setAlpha(...) method on InsetDrawable.

InsetDrawable background = 
            (InsetDrawable) dialog.getWindow().getDecorView().getBackground();
background.setAlpha(0);

EDIT (as a result of Cheok Yan Cheng's comments):

or you can actually skip casting to InsetDrawable and get the same result. Just remember that doing so will cause the alpha to be changed on the InsetDrawable itself and not on the Drawable that is wrapped by the InsetDrawable.


retaining spacings