java.lang.ClassCastException:android.graphics.drawable.LayerDrawable不能转换为android.graphics.drawable.GradientDrawable [英] java.lang.ClassCastException: android.graphics.drawable.LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable

查看:671
本文介绍了java.lang.ClassCastException:android.graphics.drawable.LayerDrawable不能转换为android.graphics.drawable.GradientDrawable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我想每个ListView项改变背景颜色。而对于我使用的形状这层列表。
这里是我的code

In my application I am trying change background color for each listView item. And for that I am using shapes which in layer-list. Here is my code

drop_shadow.xml

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>

main.xml中

main.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

When I call this method I have ClassCastException

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

    }

我怎么会从LayerDrawable得到GradientDrawable?

How could I get GradientDrawable from LayerDrawable?

推荐答案

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

you can create gradient drawable dynamically.. use below class

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

这篇关于java.lang.ClassCastException:android.graphics.drawable.LayerDrawable不能转换为android.graphics.drawable.GradientDrawable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆