Android: create gradient background via XML

In the previous post we have created a blue actionbar header. The header was blue, but the body of the app was still white. In this short tutorial I show you how you can change the background of your app using color-codes and adding a gradient in the color. The screenshot displays the background color we will make with this turoial. In case, your wondering where the actionbar comes from see my previous tutorial.

First, open your resources folder from your Eclipse project. Create a gradient.xml file in your drawable folder. In this gradient.xml we will define the color and the gradient. We do this by defining the start and end color and the number of degrees how the color need to change from the start value till the end value.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#3B5998"
        android:endColor="#00000000"
        android:angle="45"/>    
</shape>

Now open the layout from your activity in which you want to set this gradient background. In our case, activity_main.xml. Set the android:background=”@drawable/gradient”, in the parent view, in our case the Relative layout.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/gradient" >
    
      <include
        android:id="@+id/include1"
        layout="@layout/actionbar" />

</RelativeLayout>

Note that the tag refers to the inclusion of the actionbar which I explained in my previous tutorial.

1 Response

  1. Ariel March 5, 2015 / 4:06 am

    Helpful, thanks!

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*