Haji
Haji

Reputation: 1775

Setting Gradient Background programmatically

I have an image on which I'm putting a colored overlay, like this (the colors are taken from here):

layout/list_item_view.xml

<View 
    android:id="@+id/image_cover_gradient"
    android:layout_width="fill_parent"
    android:layout_height="80dip"
    android:layout_alignParentTop="true"
    android:layout_marginTop="70dp"
    android:background="@drawable/gradient_blue"        
    />

drawable/gradient_blue.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
    <shape>
        <gradient
            android:angle="90"
            android:startColor="@color/CornflowerBlue"
            android:endColor="@color/Transparent"
            android:type="linear" />
    </shape>
</item>
</selector>

This always puts a blue overlay (CornflowerBlue) and it works as expected.

Now I'm trying to do this programatically and followed some stackoverflow answers (such as this), but still can't make it work. Here's my code:

private void setColor(int color){
    View gradientCover = view.findViewById(R.id.image_cover_gradient);
    // this FAILS because it's a StateListDrawable
    //GradientDrawable coverGd = (GradientDrawable) gradientCover.getBackground();
    //coverGd.setColor(color);

    //this doesn't seem to work either (I don't see any effect on the image)
    GradientDrawable drawable = new GradientDrawable(
            Orientation.BOTTOM_TOP, new int[] { color, resources.getColor(R.color.Transparent) 
            });
    StateListDrawable sld = new StateListDrawable();
    sld.addState(new int[] { android.R.attr.startColor, android.R.attr.endColor}, drawable);
    gradientCover.setBackground(sld);
}

Upvotes: 7

Views: 11599

Answers (1)

Haji
Haji

Reputation: 1775

As @pskink suggested - removing the StateListDrawable solved it:

GradientDrawable drawable = new GradientDrawable(
    Orientation.BOTTOM_TOP, new int[] { color, resources.getColor(R.color.Transparent) 
});     
gradientCover.setBackground(drawable);

Upvotes: 11

Related Questions