How to set color using integer?

22,348

Solution 1

I got the solution. Just a work around with Hexadecimal as below:

Integer.toHexString(colour);

Which returns the hexadecimal string for your integer, again if you just use it by

mainLayout.setBackgroundColor(Integer.parseInt(hexVal,16));

it wont work. You need to add mask as

mainLayout.setBackgroundColor(0xff000000 + Integer.parseInt(hexVal,16));

This has resolved the problem

Solution 2

Try passing:

mainLayout.setBackgroundColor(Color.parseColor("#FFFFFF"));

Solution 3

The question is very old. Still this answer would help someone who search a way to set the color directly as an integer.

If you look at the android documentation, the constant value for white is -1 and black is -16777216. (i.e.) the whole color int value range is (-1 to -16777216). So you can simply add the integer value to -16777216.

For example if you want to set color white whose decimal representation is 16777215 (0xffffff), then 16777215 - 16777216 will give you -1 the color constant for black in android.

Share:
22,348
Arun
Author by

Arun

Android and Blackberry mobile application developer.

Updated on November 02, 2021

Comments

  • Arun
    Arun over 2 years

    How can i convert color code in integer ex: 13369395 to android specific. Since 13369395 is also an integer i tried doing

    mainLayout.setTextColor(13369395);
    

    but its not working.

    I also tried converting 13369395 to hexadecimal like:

    mainLayout.setBackgroundColor(Integer.parseInt(13369395 +"", 16)+0xFF000000);
    

    but it also didn't help.

  • Arun
    Arun over 12 years
    I got the solution. Just a work around with Hexadecimal as below: Integer.toHexString(colour); which returns the hexadecimal string for your integer, again if you just use it by mainLayout.setBackgroundColor(Integer.parseInt(hexVal,16)‌​); it wont work. You need to add mask as mainLayout.setBackgroundColor(0xff000000 + Integer.parseInt(hexVal,16)); This has resolved the problem. Thanks
  • LokiDroid
    LokiDroid about 10 years
    mainLayout.setBackgroundColor( #0BB5FF); This is not supported as of Java 1.6