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?
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);
They are both a subclass of Drawable, so you can't cast them to each other, only to their parent classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With