How to get background color in TextView?

How to get the background color of a TextView?

When I click on TextView, I want to change the background color to match the background color used.

TextView does not have a method like:

getBackgroundResource() 

Edit: I would prefer to get the background color status.

+7
source share
4 answers

If you want the background color code, try the following:

 if (textView.getBackground() instanceof ColorDrawable) { ColorDrawable cd = (ColorDrawable) textView.getBackground(); int colorCode = cd.getColor(); } 
+13
source

ANSWER:

we cannot use constants like color.red or color.white.

we need to understand how

 int intID = (ColorDrawable) holder.tvChoose.getBackground().getColor(); 

represent it and we have a fake color id

0
source

ColorDrawable.getColor() will only work with API levels above 11, so you can use this code to support it from the start. I use reflection below API level 11.

  public static int getBackgroundColor(TextView textView) { Drawable drawable = textView.getBackground(); if (drawable instanceof ColorDrawable) { ColorDrawable colorDrawable = (ColorDrawable) drawable; if (Build.VERSION.SDK_INT >= 11) { return colorDrawable.getColor(); } try { Field field = colorDrawable.getClass().getDeclaredField("mState"); field.setAccessible(true); Object object = field.get(colorDrawable); field = object.getClass().getDeclaredField("mUseColor"); field.setAccessible(true); return field.getInt(object); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } return 0; } 
0
source

If you are using AppCompat , use this:

 ViewCompat.getBackgroundTintList(textView).getDefaultColor(); 

Side note: be careful if you click on ColorDrawable because it might throw a ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable .

0
source

All Articles