以编程方式设置渐变背景

时间:2014-09-01 14:16:27

标签: android android-layout android-drawable

我有一张图片,我正在放置一个彩色叠加层,就像这样(颜色来自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),它按预期工作。

现在我正在尝试以编程方式执行此操作并遵循一些stackoverflow答案(例如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 个答案:

答案 0 :(得分:7)

正如@pskink建议的那样 - 删除StateListDrawable解决了它:

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