Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: android.graphics.drawable.LayerDrawable cannot be cast to android.graphics.drawable.GradientDrawable

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

<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

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

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

    }

How could I get GradientDrawable from LayerDrawable?

like image 520
fish40 Avatar asked Aug 05 '13 10:08

fish40


2 Answers

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

and use this class as below

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);
like image 92
Sanket Kachhela Avatar answered Sep 28 '22 14:09

Sanket Kachhela


They are both a subclass of Drawable, so you can't cast them to each other, only to their parent classes.

like image 30
pshegger Avatar answered Sep 28 '22 14:09

pshegger