In this post I would like to share my findings about defining and using shapes. A shape is an XML file that defines a geometric shape, including strokes, colors and gradients
To define a shape:
1. Create a new Android XML file in the folder res/drawable
2. Make sure the root element of the file is <shape >. (If it’s not, then change it manually)
3. Inside the <shape> element, press CTRL + Space to reveal all the available elements you can use to define a shape:
As you can see, the elements are pretty self explanatory. To reveal the attributes of an element, put the cursor inside that element and press CTRL + Space:
4. Once the shape is defined, you can specify it as a background resource to any view: android:background=”@drawable/myshape”
res/drawable/boxbg.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <stroke android:width="2dp" android:color="#FFFFFF" /> <corners android:radius="5dp" /> <gradient android:angle="270" android:centerColor="#6E7FFF" android:endColor="#142FFC" android:startColor="#BAC2FF" /> </shape>
res/drawable/box2bg.xml:
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" > <solid android:color="#4D9611" /> <stroke android:width="4dp" android:color="#FFFB00" /> </shape>
res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- First box, boxbg.xml -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_margin="20dp"
android:background="@drawable/boxbg"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textColor="#000"
android:textSize="20dp" />
</LinearLayout>
<!-- Second box, box2bg.xml -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp"
android:layout_margin="20dp"
android:background="@drawable/box2bg"
android:orientation="vertical"
android:padding="7dp" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textColor="#FFF"
android:textSize="20dp" />
</LinearLayout>
</LinearLayout>
The final output should look like this:



