Peter Ajtai
Peter Ajtai

Reputation: 57705

How do you determine the background color of a TextView?

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(...).

Upvotes: 3

Views: 4155

Answers (3)

Abhijit Srivastava
Abhijit Srivastava

Reputation: 194

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>

Upvotes: 0

David C. Sainte-Claire
David C. Sainte-Claire

Reputation: 2481

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();

Upvotes: 1

David C. Sainte-Claire
David C. Sainte-Claire

Reputation: 2481

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

Upvotes: 1

Related Questions