【发布时间】: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);
}
【问题讨论】:
-
摆脱StateListDrawable,只需要GradientDrawable
-
可能需要它的 Kotlin 代码:stackoverflow.com/a/54495750/6247186
标签: android android-layout android-drawable