Gradient Background in Android

An easy way to change the style of your mobile application is to add gradient backgrounds to the view components. In this example, we are adding a gradient background to the elementes of a list view.

No gradient

Firstly, define the colors in your Android xml file of resources. If you do not have a file of color resources, create it in the /res/values folder.

Create Resource File

In this example, we are using two different tones of grey.

<resources> 
  <color name="greyMed">#C9C9C9</color> 
  <color name="greyLgt">#ECECEC</color> 
</resources> 

Next step is to create a drawable resource in /res/drawable folder with Shape as root element.

Create gradient xml file

In a list view item, the shape is a rectangle and the gradient is created inside this shape. The gradient tag has the startColor and endColor attributes, that configure the gradient color, and the angle attribute that configure the angle of the gradient in degrees.

Gradient 2 colors

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
  <gradient 
    android:startColor="@color/greyMed" 
    android:endColor="@color/greyLgt" 
    android:angle="90"> 
  </gradient> 
</shape>

The gradient tag has also the attribute centerColor.

gradient 3 colors

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
  <gradient 
    android:startColor="@color/greyMed" 
    android:centerColor="@color/greyLgt" 
    android:endColor="@color/greyMed" 
    android:angle="90"> 
  </gradient> 
</shape>

Or we can change the angle. The angle is an integer value that must be a multiple of 45. A value of 0 is left to right or a value of 90 is bottom to top.

Gradient 180 angle

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> 
  <gradient 
    android:startColor="@color/greyMed" 
    android:endColor="@color/greyLgt" 
    android:angle="135"> 
  </gradient> 
</shape>

Finally, another important attribute is the type. The attribute type has three valid values:

  • “linear”. This is the default value. A linear gradient as the previous examples.
  • “radial”. It requires to specify the attribute gradientRadius which is a float value.
  • “sweep”. A sweeping line gradient.
Share Button

2 Comments

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload the CAPTCHA.