papium
papium

Reputation: 43

How to retrieve a view's background color and compare it to a color resource

I'm trying to compare whether the background color of one of my views is equal to a color resource I created and haven't found anything that works.

I'm willing to use any method, whether converting to HEX or String or Int, as long as it works. Here's an example of my current method.

I set the background color of a view with:

chosenColor.setBackgroundColor(getResources().getColor(R.color.tag_pink));

When I retrieve it using this method:

ColorDrawable chosenColorBox = (ColorDrawable) chosenColor.getBackground();  
int colorId =  chosenColorBox.getColor();

colorId == `-611329` 

Using Integer.toString on R.color.tag_pink shows the value as 2130968581 which obviously can't be compared in an if statement" with the retrieved value.

What's the best way to do this so I don't have to resort to hard-coding the individual values, which prevents me from adjusting the color resources?

Upvotes: 4

Views: 2656

Answers (2)

Md. Sajedul Karim
Md. Sajedul Karim

Reputation: 7055

Just simple Answer:

int viewColor=((ColorDrawable) YOUR_VIEW.getBackground()).getColor();

if(viewColor==Color.parseColor("#ffffffff"){
  //Color matched
}

Upvotes: 2

Rayne
Rayne

Reputation: 2660

Try to compare the color to Context.getResources().getColor(R.color.tag_pink) instead of the resource's ID (which is not the color!). The returned value represents the color in the form of 0xAARRGGBB.

Upvotes: 5

Related Questions