How to 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.

We are going to create gradients like these:

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 version="1.0" encoding="utf-8"?>  
<shape  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:angle="0"
        android:startColor="#000000"
        android:endColor="#000000"
        android:centerColor="#97CF4D" />
</shape>  

And that is basically it. You now have a gradient shape drawable ready to use.

How to use our Gradient Shape Drawable file

In your layout file (main.xml for example), enter the following code:

<?xml version="1.0" encoding="utf-8"?>  
<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>  

The android:background=”@drawable/gradient” uses our newly created gradient.xml file in the drawable folder (or drawable-mdpi folder), and the result you can see on the first image!

Please share this article.

comments powered by Disqus