How can I fix GradientDrawable cannot be cast to ColorDrawable issue?
Asked Answered
M

1

6

I have a code snippet to show you below and I am trying to change view's(v) background. I'll get color code from a TextView(dragged) and change View(v)'s background by using this code. But I get an error as indicate above. How can I fix it? Where is the problem? Thanks.

ColorDrawable cd = (ColorDrawable)dragged.getBackground();
    int colorCode = cd.getColor();
    v.setBackgroundColor(colorCode);
Muddle answered 19/2, 2014 at 12:6 Comment(8)
Please, describe in general what is your idea and what you want to do? Set background of textview to another view?Syphilis
I want to change TextViews background color. I will get this color from another TextView(dragged). Also I need this color's code to use in my code to store an array that store color's code.Paramedical
looks like you use gradient as background for textview. isn't it?Syphilis
No. I just use shape.xml to make TextView(dragged) oval. Is it can cause this? ıf it is, what should I do?Paramedical
maybe you can try to use whole background(getBackground, setBackground) drawable instead of color. But it won't help to store color. Please try to debug and check type of drawable object when you call getBackground. Is it GradientDrawable?Syphilis
When I remove shape.xml there is no problem and TextViews look rectangle but I want to this oval. Is there another way to oval by using above my code? Because I need both of them? If not I continue as rectangle textViewsParamedical
if you want shape - you only able to get current background drawable and set it to another view. If you want to get color - try to debug up. Check drawable that you get from getBackground() and inspect all fields, drawable type and documentation on this drawable type.Syphilis
The best way to change my method :) Thanks a lotParamedical
T
0

If you want to just assign a background of one view to another and not just the color you can use the following code

Drawable drawable = dragged.getBackground();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    v.setBackgroundDrawable(drawable );
}else{
    v.setBackground(drawable);
}

However if you want to get only the color then you will have to identify in advance what types of drawable are being assigned to view. Then use instanceof to handle how to get background color for corresponding drawable.

Trubow answered 17/5, 2016 at 6:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.