alizeyn
alizeyn

Reputation: 2420

Get Background Color of a View in hex

I want to get background color of a view in hex format.

for example consider int getViewBackgroundColor(View view) my excepted return vaule is 0Xff256e78.

How could I do this?

thanks.

Upvotes: 4

Views: 4729

Answers (4)

Omar Hemaia
Omar Hemaia

Reputation: 314

This answer is not different from the other answers, but it's the shortest:

((ColorDrawable)yourView.getBackground()).getColor()

Upvotes: 0

Nikhil Borad
Nikhil Borad

Reputation: 2085

LinearLayout layout = (LinearLayout) findViewById(R.id.lay1);
ColorDrawable viewColor = (ColorDrawable) layout.getBackground();
int colorId = viewColor.getColor();

After getting as integer type of color, now you have to convert to hexadecimal:

String hexColor = String.format("#%06X", (0xFFFFFF & colorId));

Hope this helps..

Upvotes: 7

bayram.cicek
bayram.cicek

Reputation: 343

Here is the answer in Kotlin language:

var view: View = findViewById(R.id.bg_view_id)
var draw: ColorDrawable = view.background as ColorDrawable
var color_id = draw.getColor()

Log.i("UYARI-INFO: ", Integer.toHexString(color_id))

Output in Logcat will be:

I/UYARI-INFO:: ffffd8af

Upvotes: 0

Saurav Prakash
Saurav Prakash

Reputation: 654

The following code will get the background color of a view and convert it to the int representation of the color.

ColorDrawable buttonColor = (ColorDrawable) myView.getBackground();
int colorId = buttonColor.getColor();

Upvotes: 0

Related Questions