The Android SDK provides a very powerful feature which helps you create cool looking backgrounds for your views and widgets. The best part is you do not have to create or resize any images to fit any device screens and the whole thing is based on simple xml files. And you don’t have to waste time in scaling a lot of images.
To create a custom background file create a custom XML file in the /res/drawable folder in the project and later it can be referenced using the android:background attribute of any view or widget.
You would need to use the <shape> element in the XML file and then define the attribute of the shape, the shape can be a rectangle, oval, line or ring. Though the most commonly used shape is rectangle.
In the example below we create a rectangle with rounded corners and use a gradient to color the background. Also the rounded rectangle has a border of 5 dip.
Right click on the res folder in the project >> New >> Android XML File
Step 2: Select the Resource Type as Drawable and select the Root Element as shape and name the file eg. Gradientbg.
This will create a gradientbg.xml under the drawable folder under the res folder and open the XML file in the code window.
Step 3: Modify the xml file as follows:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" > <gradient android:angle="270" android:endColor="#CEECF5" android:startColor="#00BFFF" android:type="linear" > </gradient> <corners android:radius="20dip" /><stroke android:width="5dip" android:color="#000" /></shape>
android:shape defines the shape of the background it coud be rectangle,oval,ring or line.
<gradient> tag provides the startcolor and the endcolor and the angle in multiples of 45, also type which could be linear,radial or sweep.
<corners> only applies to the shape rectangle and the radius provides the degree of roundness for the corners.
<stroke> provides a border to the rectangle which has a width and a color.
Once the XML file is compiled it can be used in any view or widget by defining the android:background = “@drawable/gradientbg” where gradientbg is the XML file name.
The following screen shot shows the background applied on the whole activity by applying the background on the root layout.
In the next screenshot the same background is applied on a button widget.