Can GradientColor be used to define a gradient for a fill or stroke entirely in XML?

I’ve finally made it work. Gradient color feature is not supported yet in Android Studio (current ver is 2.2) so it doesn’t help you with autocomplete but marks gradient tag as error instead. Nevertheless, the feature does actually work, I’ve tested it successfully on Nexus 5X / API 24. Of course, you have to use an API 24+ device because otherwise this feature is not supported by OS.

First, you need to add color resource file like this:

<?xml version="1.0" encoding="utf-8"?>
<gradient xmlns:android="http://schemas.android.com/apk/res/android"
    android:startColor="#FFFFFF"
    android:centerColor="#0000FF"
    android:endColor="#00FFFF"
    android:angle="145"
    android:startX="30"
    android:endX="70"
    android:startY="30"
    android:endY="70"
    android:type="linear"/>

Please pay attention to start/end parameters as I found they are essential for vector gradients.

Place this file into res/color folder under some name. I’ve named it gradient.xml so the full path is res/color/gradient.xml. After that you can refer to this resource in color attributes, including vector path colors:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="120dp"
    android:height="120dp"
    android:viewportWidth="120.0"
    android:viewportHeight="120.0">

    <path
        android:name="play_triangle"
        android:pathData="M 30 30 L 30 90 L 80 60 z"
        android:strokeWidth="10"
        android:strokeColor="@color/gradient"/>

</vector>

Notice the reference to gradient color resource in strokeColor. Hope this helps!

Leave a Comment