设置渐变背景通过编程

问题描述:

我有一个形象上我把一个彩色叠加,像这样(的颜色从here拍摄):设置渐变背景通过编程

布局/ 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"   
    /> 

绘制/ 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> 

这总是会产生一个蓝色覆盖层(CornflowerBlue),并且它按预期工作。

现在我试图以编程方式执行此操作,并遵循一些*答案(如this),但仍然无法使其工作。这里是我的代码:

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); 
} 

感谢您的帮助。

+1

摆脱StateListDrawable的,你需要的是GradientDrawable – pskink 2014-09-01 14:21:56

由于@pskink建议 - 去除StateListDrawable解决它:

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

,你为什么张贴吗? – k0sh 2014-09-02 08:59:00