【问题标题】:Setting Gradient Background programmatically以编程方式设置渐变背景
【发布时间】:2014-10-25 19:08:06
【问题描述】:

我有一张图片,我在上面放了一个彩色叠加层,就像这样(颜色取自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"        
    />

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>

这总是会放置一个蓝色叠加层 (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);
}

【问题讨论】:

标签: android android-layout android-drawable


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-09-01
    • 1970-01-01
    相关资源
    最近更新 更多