vlio20
vlio20

Reputation: 9295

compare background color of layout in android application

I want to make an if statement in which I will compare the color of my layout background color, something like this:

 RelativeLayout screen = (RelativeLayout) findViewById (R.id.screen);
 if(screen.getBackgroundColor() == "#FFFFFFFF"){
    //do something...
 }
 else{
   //do something else...
 }

I can't find out how to get the background color. I am setting the color by: screen.setBackgroundColor(Color.parseColor("#000000"));

Upvotes: 2

Views: 4268

Answers (2)

Marcin Orlowski
Marcin Orlowski

Reputation: 75629

There's no direct getBackgroundColor(), but if you really need to know the color value, you should retrieve view's Paint object and get color from it:

Paint viewPaint = ((PaintDrawable) view.getBackground()).getPaint();
int colorARGB = viewPaint.getColor();

Note this contains alpha as well, so be careful with your comparison (or get rid of alpha if you just need to compare RGB:

int colorRGB = colorARGB & 0x00ffffff;

This will work on all API levels.

EDIT

As for the comparision - once you got color retrieved you can use Color.parseColor() and compare the result usual way:

if( colorRGB == Color.parseColor("#ffffff") ) {
   // matches...
}

or same with ARGB:

if( colorARGB == Color.parseColor("#ffffffff") ) {
   // matches...
}

And if you are doing this frequently (like in. list adapter) I'd parse it once and store the results for reuse.

Upvotes: 3

Dimitris Makris
Dimitris Makris

Reputation: 5183

In can you use API level 11+, you can cast the screen.getBackground() into a ColorDrawable and then call the method getColor(). Unfortunately this method is not available for API level < 11.

Hope this helps!

Upvotes: 2

Related Questions