5

在我的应用程序中,我正在尝试更改每个 listView 项目的背景颜色。为此,我正在使用图层列表中的形状。这是我的代码

drop_shadow.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle">

            <gradient android:startColor="#B7B7B7"
                      android:endColor="#A1A1A1"
                      android:angle="270"/>
            <corners android:radius="10dp" />

        </shape>
    </item>

    <item android:top="1px">

        <shape android:shape="rectangle">

            <solid android:color="@color/color11"/>
            <corners android:radius="10dp" />
        </shape>

    </item>

</layer-list>

主要的.xml

<RelativeLayout 
                android:orientation="vertical"
                android:id="@+id/mainLayout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@drawable/drop_shadow"/>

当我调用此方法时,我有 ClassCastException

 private void setRoundedBackground(View view,int color){
        GradientDrawable gradientDrawable;
        gradientDrawable = (GradientDrawable) view.getBackground().mutate();
        gradientDrawable.setColor(getResources().getColor(color));
        gradientDrawable.invalidateSelf();

    }

我怎样才能从 LayerDrawable 获得 GradientDrawable?

4

3 回答 3

7

你可以动态创建渐变绘制..使用下面的类

    import android.graphics.drawable.GradientDrawable;

    public class SomeDrawable extends GradientDrawable {

    public SomeDrawable(int pStartColor, int pCenterColor, int pEndColor, int pStrokeWidth, int pStrokeColor, float cornerRadius) {
        super(Orientation.BOTTOM_TOP,new int[]{pStartColor,pCenterColor,pEndColor});
        setStroke(pStrokeWidth,pStrokeColor);
        setShape(GradientDrawable.RECTANGLE);
        setCornerRadius(cornerRadius);
    }
 }

并使用这个类如下

SomeDrawable drawable = new SomeDrawable(Color.parseColor("Start Color Code"),Color.parseColor("Center Color Code"),Color.parseColor("End Color Code"),1,Color.BLACK,00);
yourLayout.setBackgroundDrawable(drawable);
于 2013-08-05T10:15:28.720 回答
1

它们都是 Drawable 的子类,因此您不能将它们相互转换,只能转换为它们的父类。

于 2013-08-05T10:09:16.757 回答
0

我想最好使用 separacte colors.xml 文件作为形状的颜色,并使用标签,你可以删除 .

毕竟你的形状都是一样的,都是矩形的。

以前我遇到了同样的错误,因为我在同一个 xml 中使用和。

于 2018-05-08T06:16:24.450 回答