7

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);
}
2
  • 2
    get rid of StateListDrawable, all you need is GradientDrawable Commented Sep 1, 2014 at 14:21
  • Kotlin code for whom may need it: stackoverflow.com/a/54495750/6247186 Commented Feb 2, 2019 at 17:50

1 Answer 1

11

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.