Android — How to set gradient color as background

Konstantinos Evangelidis
2 min readAug 8, 2020

--

First of all… What are gradients?
Gradients, also known as color transitions, are a gradual blending from one color to another color. So we need two colors in hex format. One color is gonna be the starting color and the other the ending color. We can use any two colors. For this example i’m gonna use #ff2d9a59 and #ff23729a.

Lets take of a gradient color

gradient color background

Follow the next steps to set this color as background

Step 1:

First of all we have to create a new Drawable Resource File under res/drawable folder.

Step 2:

Copy this code

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

There are 4 main attributes you have to know:

  1. android:startColor:
    It is the starting color of the gradient.
  2. android:endColor:
    It is the ending color of the gradient.
  3. android:centerColor:
    It will come in the center of the screen.
  4. android:angle:
    It is a special angle and works only with the multiple of 45 including 0. So you can give 0, 45, 90, 135 and so on. Depending on the angle gradient position will change on the screen.

For example using angle = 0 we will have this design

0 Angle

and using angle = 135 is gonna be like this

Step 3:

Use background attribute in xml file to use the the file we just created. You can use it in any xml element adding this line
android:background=”@drawable/gradient”

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient"
tools:context=".MainActivity">

</androidx.constraintlayout.widget.ConstraintLayout>

Source code here

Feel free to leave any comment.

Thank you very much

--

--

Responses (2)