
Gradients are created by gradually transitioning from one color to another. There are many different types of gradients that can be used in various situations. Radial gradients, for example, can be used to create a sense of circular motion in an image and linear gradients can be used for backgrounds or as a border for text.
How to create a gradient background in Android?
First, we will see an example of a linear gradient.
Create an XML file in the drawable folder. To do this right-click on the drawable folder. Then, hover over New, then click on the Drawable Resource File option (See the screenshot below).

Give a name to the XML file. I have named it gradient_background.

Now create the gradient like this –
<?xml version="1.0" encoding="utf-8"?>
<shape
android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor = "#0CFAE1"
android:endColor = "#C238E6"
android:angle = "45"
android:type = "linear" />
</shape>
Now use the android:background attribute to apply the gradient on the layout. See the activity_main.xml file below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:background="@drawable/gradient_background"
tools:context=".MainActivity" />
Output :

Now, let’s see an example of a radial gradient.
<?xml version="1.0" encoding="utf-8"?>
<shape
android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:gradientRadius="350dp"
android:startColor = "#0CFAE1"
android:centerColor="#A0D6D6"
android:endColor = "#DE79F8"
android:type = "radial" />
</shape>
Output :

Now, let’s see an example of a sweep gradient.
<?xml version="1.0" encoding="utf-8"?>
<shape
android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:endColor="#00ACC1"
android:centerColor="#5E35B1"
android:startColor="#E040FB"
android:centerX="0.6"
android:centerY="0.8"
android:type="sweep"/>
</shape>
Output :

Leave a Reply