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.

Share:
18,872

Related videos on Youtube

OrSmolnik
Author by

OrSmolnik

Updated on September 15, 2022

Comments

  • OrSmolnik
    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
    OrSmolnik almost 11 years
    i edit my question: how i get from this the resId of the color?
  • OrSmolnik
    OrSmolnik almost 11 years
    i tried this, but after the first line in your answer i get cd is null
  • Gokhan Arik
    Gokhan Arik almost 11 years
    How do you set background of your TextView? To use this code it has to be Color, not Gradient or other kind of Drawable
  • OrSmolnik
    OrSmolnik almost 11 years
    it was because i didnt set background in the first appearance. i fixed thet, but now cd.getColor() returns me -1
  • OrSmolnik
    OrSmolnik almost 11 years
    ok, 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
    Gokhan Arik almost 11 years
    This 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
    Albert Vila Calvo over 6 years
    Be careful: this can throw an Exception: java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
  • Gokhan Arik
    Gokhan Arik over 6 years
    True. 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.