Gradient background for a view

If you still haven’t switch to Jetpack Compose, and you create your layout in XMLs you may wonder, how to create great looking gradient background for a View. Here’s the quick guide.

  1. Create new xml file under your drawables, like my_gradient_background.xml. It has to have few proprieties like:
android:startColor="@color/green"
android:centerColor="@color/blue"
android:endColor="@color/red"
android:angle="90"

Play around to see what effect you can achieve. Here’s how it can look in your code, and below on the preview:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@android:color/holo_green_dark"
android:centerColor="@android:color/holo_blue_dark"
android:endColor="@android:color/holo_red_dark"
android:angle="45" />
</shape>
Preview of your gradient background

2. Ok, now it’s time to use your background for some view. Let’s say you wanted to use this for a button background. Open you layout xml and add your gradient xml as a parameter android:backgroud for the view you need. Something like that:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:background="@drawable/my_gradient_background/>
And here’s the effect for your button

And that’s it. Hope you enjoyed this small tutorial.

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *