How do I get the background color of a TextView?
18,872
Solution 1
If you want to get color code of the background try this:
if (textView.getBackground() instanceof ColorDrawable) {
ColorDrawable cd = (ColorDrawable) textView.getBackground();
int colorCode = cd.getColor();
}
Solution 2
In Kotlin:
val cd = view.background as ColorDrawable
val colorCode = cd.color
Solution 3
If you are using AppCompat
use this:
ViewCompat.getBackgroundTintList(textView).getDefaultColor();
Side note: be careful if you cast to ColorDrawable
, because it can throw a ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
.
Related videos on Youtube
Author by
OrSmolnik
Updated on September 15, 2022Comments
-
OrSmolnik over 1 year
How do I get the background color of a TextView?
When I press the TextView, I want to change the background color according to the background color that is in use.
TextView does not have a method such as:
getBackgroundResource()
Edit: I would prefer to get the resId of the background color.
-
OrSmolnik almost 11 yearsi edit my question: how i get from this the resId of the color?
-
OrSmolnik almost 11 yearsi tried this, but after the first line in your answer i get cd is null
-
Gokhan Arik almost 11 yearsHow do you set background of your TextView? To use this code it has to be Color, not Gradient or other kind of Drawable
-
OrSmolnik almost 11 yearsit was because i didnt set background in the first appearance. i fixed thet, but now cd.getColor() returns me -1
-
OrSmolnik almost 11 yearsok, its very strange. if i first set the background to color.black the getColor() returns me other number (not -1) but it still not the same resID color.black . my "if" is to check if the beckround is equals to white backround, so i replace "if (cd.getColor() == color.white)" to "if (cd.getColor() == -1)" . and it works!
-
Gokhan Arik almost 11 yearsThis numbers are
constant Color IDs
of the some pre-defined colors. You can see the list here : (developer.android.com/reference/android/graphics/Color.html) The reason it returns -1 is that, White has -1 constant value. You will see in the list. -
Albert Vila Calvo over 6 yearsBe careful: this can throw an
Exception
:java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
-
Gokhan Arik over 6 yearsTrue. RippleDrawable wasn't introduced at the time I answered this question. You would have to check instance of background object before casting. The answer assumes you are using
ColorDrawable
.