Android supports all sorts of “drawable” objects (the Bitmap drawable, which can contain images in formats like PNG and JPG, is one example). The one we are going to talk about today is so-called Shape drawable.

Shape drawables are defined with a simple XML syntax and stored in the drawable folder of an Android solution. Several basic shapes are supported, including rectangles (with optional rounded corners) and ovals. The border and fill of a shape can be specified—the user can choose a solid fill color or a multistep gradient. The Android designer in MonoDevelop is actually smart enough to interpret XML drawables, so you can change them and see the result appear live in MonoDevelop’s Android layout designer as you are building your application!

A standalone shape drawable is probably not very useful, but shapes can be immensely helpful when used together in conjunction with other Views. You can use a combination of simple shapes and other elements for simple widget theming. In the following image, which was first shown in my expandable ListView blog post, you can see three different shape drawables in action:


First, the circle around the coffee cup is an oval drawable filled with a semi-transparent color to darken the main header background color. The following XML is the source code for that shape:

In the following XML layout, you can see the shape referenced in the android:background attribute:

To force the oval shape to be square, you have to set the size of the FrameLayout accordingly. The necessary value will depend on your application. You can even set it dynamically, though that has to be done in code.

Second, the bottom bar where the location and date appear is a rectangle shape filled with a gradient to give it volume. Gradients like that one are a convenient way to add some eye candy to your UI elements. For more details, see the Android graphics talk (the relevant part starts at 3:10) that Google developers Chet Haase and Romain Guy presented at Devoxx.

The XML code for the bar shape is given below:

In this example, I combined the <solid/> element to paint my base color and the <gradient/> element to perform the shading on top of it.

Again, to apply the effect, simply use the android:background attribute in one of your layout elements:

Finally, the border (with round corners) that is displayed around the whole UI widget is also a shape drawable:

In this case, since we only care about the border, we set the filling color of the shape to be transparent. The <stroke/> element defines your border while the <corners/> element makes it round.

As a final treat, if you combine things, you can also make a fancy header using shapes:


The following code defines the Shape XML (notice the left padding value, which is used for indenting):

The following code defines the TextView XML (as always, the shape is registered in android:background attribute):

Now go add a bit of “woowoo” to your app!