title: Setting Gradient Background programmatically
body: <p>I have an image on which I'm putting a colored overlay, like this (the colors are taken from <a href="https://stackoverflow.com/a/7323234/977890">here</a>):</p>
  
  <p>layout/list_item_view.xml</p>
  
  <pre><code>&lt;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"        
      /&gt;
  </code></pre>
  
  <p>drawable/gradient_blue.xml</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
  &lt;item&gt;
      &lt;shape&gt;
          &lt;gradient
              android:angle="90"
              android:startColor="@color/CornflowerBlue"
              android:endColor="@color/Transparent"
              android:type="linear" /&gt;
      &lt;/shape&gt;
  &lt;/item&gt;
  &lt;/selector&gt;
  </code></pre>
  
  <p>This always puts a blue overlay (CornflowerBlue) and it works as expected. </p>
  
  <p>Now I'm trying to do this programatically and followed some stackoverflow answers (such as <a href="https://stackoverflow.com/a/6348761/977890">this</a>), but still can't make it work. Here's my code:</p>
  
  <pre><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);
  }
  </code></pre>