Adding shadows to views in Android using 9-patch image
This is a topic that has been discussed quite a lot in the past. But I couldn't find an easy solution that outlines the steps for creating shadows around views in Android. In this post, I will outline the process right from the beginning.
The first step is to create a png image with a shadow around it. I used photoshop to create such an image. Its really simple.
- Create a new image with Photoshop.
- Add a layer and create a black square of 4x4.
- Create a shadow on the layer by selecting the layer in layer explorer and clicking on a button titled
- Export the image as png.
If you want to skip this step, here are the images that I prepared.
The next step is to create 9-patch drawables from this image.
- Open the image in
- Create 4 black lines on the four sides of the square like the following and then save the image as
Here is the 9patch image of the black version if you don't want to create your own.
Now you can add this shadow as the background of the views you want to add the shadow to. Add
res/drawables. Here's how to add this to a linearLayout:
<LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="@drawable/shadow" android:paddingBottom="5px" android:paddingLeft="6px" android:paddingRight="5px" android:paddingTop="5px" >
The padding here is important and if you created your own image with photoshop, then you might need to change these values for your images. The rule is that the padding should be the number of pixels from a corner of the image to beginning of your shadow.