Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Create Gradient Lines with Drawables in Android

This article will show you how to create simple gradient line separators to spice up the layout a little bit.
About Drawables

First off, we are going to create a drawable. A drawable resource is graphics that can be drawn on the screen,
it can be a couple of different things, here are some examples;

Bitmaps – png, jpg or gif images
Nine-Patch image – A png that can be stretched, to create buttons of varying sizes for example
State List – Making it easier to use different images for button states for example (focused, pressed)
Shape Drawable

You can read more about drawable resources here.

Creating a Gradient Shape Drawable

In this example we are going to use the Shape Drawable, with it, we can create different shapes, we will use a Rectangle shape.

Create a new .xml file in your drawable folder (or drawable-mdpi folder) called gradient.xml, with the following code:
XML
<shape
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:shape="rectangle">
	<radient
		android:angle="0"
		android:startColor="#000000"
		android:endColor="#000000"
		android:centerColor="#97CF4D" />
</shape>


And that is basically it. You now have a gradient ready to use.
How to use our Gradient Shape Drawable file

In your layout file (main.xml for example), enter the following code:
XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout01"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <Button android:text="Button"
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></Button>
    <View android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
    <CheckBox android:text="CheckBox"
        android:id="@+id/CheckBox01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></CheckBox>
    <View android:layout_width="wrap_content"
        android:background="@drawable/gradient"
        android:layout_height="1dp"></View>
</LinearLayout>



If you look at the View widget on line 15-18 and 24-27, that is how we use our gradient drawable.

The
HTML
android:background="@drawable/gradient"
uses our newly created gradient.xml file in the drawable folder (or drawable-mdpi folder),.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)