Intro

According to the Android documentation a drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon.

There are several different types of drawables: Bitmap file, Nine-Patch file, Layer List, State List, Level List, Transition Drawable, Inset Drawable, Clip Drawable, Scale Drawable and Shape Drawable.

A shape drawable is a generic shape defined in XML. Shapes are usually used as the background of a layout or a view on screen. For example you can easily customize the look of your buttons using shapes. A shape drawable has several elements. The root element must be <shape>, and the other elements are <corners>, <gradient>, <padding>, <size>, <solid> and <stroke>.

The <corners> element creates rounded corners for the shape and it only applies when the shape is rectangle. The <gradient> element specifies a gradient color for the shape and the <padding> element specifies the padding to apply to the containing View element (this pads the position of the View content, not the shape). The <size> element specifies the size of the shape, the <solid> element – a solid color to fill the shape and the <stroke> element – a stroke line for the shape. For more information on the elements and their attributes you can check the documentation.

In this post we will show you how to create some of the most used shape drawables in Android. To create a shape drawable you need to right click on your drawable folder, select New/Drawable Resource File, after that name the file and select the root element to be shape.

Circle

A shape that has very common use. You can create a circle shape using the following code:

Gradient circle

Using the gradient element you can create a gradient circle. You can use this code to create a gradient circle:

Rounded button

You can create a rounded button shape drawable using rectangle shape with added radius attribute to the corner element. You can use this code:

 

Arrow

For the arrow drawable we will use a layer-list and two items to create the arrow, a rectangle and a rotated rectangle. You can use this code to create an arrow shape:

Ring

You can use this code to create a ring drawable:

That’s it, some of the most used shape drawables, you can experiment with the elements and attributes and create many more.

Happy coding!

 

 

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *