Skip to content

Instantly share code, notes, and snippets.

@devunwired
Created November 14, 2012 20:09
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save devunwired/4074446 to your computer and use it in GitHub Desktop.
Save devunwired/4074446 to your computer and use it in GitHub Desktop.
XML Shape Drawable for Dialog Backgrounds. Applies a fixed outer margin to keep background from fully stretching to screen edge, and allows for additional internal padding to apply to the dialog content.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Apply the margin value on the "item" element -->
<!-- This example creates a 15dp visible margin around the dialog -->
<item
android:top="15dp"
android:bottom="15dp"
android:left="15dp"
android:right="15dp">
<shape
android:shape="rectangle">
<!-- Add attributes specific to your background (e.g. corner radius, colors, etc.) -->
<!-- Set "padding" at minimum to match margin and add additional content padding as well, if desired -->
<!-- This example creates 10dp of internal padding for content -->
<padding
android:top="25dp"
android:bottom="25dp"
android:left="25dp"
android:right="25dp" />
</shape>
</item>
</layer-list>
<!-- Possible example of applying the background to your application dialogs. -->
<!-- You can also set the background directly on your dialog's content view hierarchy if you have customized the theme another way. -->
<style name="Theme.CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@drawable/background_dialog</item>
</style>
@devunwired
Copy link
Author

This is a method for implementing custom Dialog backgrounds in Android that provide outer margins and inner padding in the same fashion as developers expect from the default framework implementations. The framework achieves this through 9-patch images, which is also a great solution. This shows how to achieve the same result if your background drawable is generated in XML.

@Charlie-Green
Copy link

Helped me to realize how to add margins to shape drawables - just what the doctor ordered! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment