3

In my tests I want to make sure that a View (not an ImageView) has a certain background color. How could I do this directly by interacting with the View in question?

The background of this view is not a Drawable. It was either set in the XML or it was set using view.setBackgroundColor(...).

Peter Ajtai
  • 56,972
  • 13
  • 121
  • 140
  • Possible duplicate of [How do I get the background color of a TextView?](https://stackoverflow.com/questions/17224152/how-do-i-get-the-background-color-of-a-textview) – Albert Vila Calvo Sep 12 '17 at 13:35

3 Answers3

1

It will require you to refactor a bit, but instead of using setBackgroundColor(), you can use setBackgroundDrawable() and pass in an instance of a ColorDrawable. It really isn't anymore work than how you were doing it, and the ColorDrawable lets you set its color and also get it later on when you perform your test. All View objects respond to the getBackground() method which returns the Drawable of that instance.

That should work for you, and it doesn't really add any overhead because even if you call setBackgroundColor, Android needs to create a Drawable for you

David C. Sainte-Claire
  • 2,461
  • 1
  • 15
  • 12
  • But how would I determine the color of the drawable? Or even which drawable I got? In other words if I do: `Drawable drawable = view.getBackground();` How can I recover a color (or resource ID) from drawable? I see I can recover the opacity, but I don't see how to recover the color, and I think recovering the resource ID is not possible. – Peter Ajtai Jan 16 '12 at 20:29
  • Thanks, I'll give that a go. You should add your second response to this one, and delete the second. – Peter Ajtai Jan 16 '12 at 21:01
1

The ColorDrawable has a getColor() method that returns and int value representing its color. When you create the ColorDrawable object you would call setColor() to set the background color. Now you can compare the two int color values to see if they are equal. You need to cast it as a ColorDrawable, not the Drawable interface

ColorDrawable drawable = (ColorDrawable)view.getBackground();

David C. Sainte-Claire
  • 2,461
  • 1
  • 15
  • 12
  • 1
    Be careful: this can throw an `Exception`: `java.lang.ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable` – Albert Vila Calvo Sep 12 '17 at 12:34
0

you can use this for getting the background color of textview..

yourTextView.getBackgroundResource(R.color.white);

where color.xml is defined in res/values folder as

<color name="white">#ffffffff</color>