Home » Android » Android LinearGradient XML

Android LinearGradient XML

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m facing a small problem with the LinearGradient definition in XML. What I want is to use the constructor that accepts the array of colors and the array of positions.

This one:

    LinearGradient(float x0, float y0, float x1, float y1, 
int[] colors, float[] positions, Shader.TileMode tile)

How do I pass the array in the XML? Here’s the example of XML with gradient definition, but the simple one.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#474946"
        android:endColor="#181818"
        android:angle="270"/>
    <corners android:radius="5dp" />
</shape>
How to&Answers:

You need to do this in Java code. ShapeDrawable1.java from API Demos has an example.

Shape Drawable details what is available in xml.

Answer:

Unfortunately, the definition of GradientDrawable with XML does not allow more than three colors.

Take a look at the official reference: http://developer.android.com/reference/android/graphics/drawable/GradientDrawable.html.

Example:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#474946"
        android:centerColor="#ff0000"
        android:endColor="#181818"
        android:angle="270"/>
    <corners android:radius="5dp" />
</shape>

So, in your case you would add one more color using android:CenterColor.
But for more than three colors, you’ll even need to do it with Java.

Answer:

@Juriy, @ErickPetru:

+1 for ErickPetru’s answer. Although I’d like to mention that there is one more feature available: One cannot only specify the centerColor, but also a center offset, which allows for some more flexibility and sometimes helps to avoid the necessity for Java coding.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <corners
        android:radius="5dp" />
    <gradient
        android:type="linear"
        android:startColor="#FF000000"
        android:centerColor="#FF303030"
        android:endColor="#FFE0E0E0"
        android:centerX="0.2"
        android:centerY="0.3"
        android:angle="270" />
</shape>

Answer:

You have an option if you are creating a Gradient on java.

LinearGradient lg = new LinearGradient(0, 0, width, height,
            new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
            new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);

Set this to your view’s background.