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);
Utku Soytaş
  • 1,475
  • 2
  • 19
  • 30
  • Please, describe in general what is your idea and what you want to do? Set background of textview to another view? – x90 Feb 19 '14 at 12:20
  • I want to change `TextView`s 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. – Utku Soytaş Feb 19 '14 at 12:24
  • looks like you use gradient as background for textview. isn't it? – x90 Feb 19 '14 at 15:06
  • No. I just use shape.xml to make `TextView`(dragged) oval. Is it can cause this? ıf it is, what should I do? – Utku Soytaş Feb 19 '14 at 22:29
  • 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? – x90 Feb 20 '14 at 07:08
  • 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 textViews – Utku Soytaş Feb 20 '14 at 09:43
  • 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. – x90 Feb 20 '14 at 10:26
  • The best way to change my method :) Thanks a lot – Utku Soytaş Feb 21 '14 at 06:58

1 Answers1

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.

Anirudha Agashe
  • 3,510
  • 2
  • 32
  • 47