How to set color using integer?

How can I convert the color code to integer ex: 13369395 in android specific. Since 13369395 is also an integer, I tried to do

mainLayout.setTextColor(13369395); 

but does not work.

I also tried converting 13369395 to hexadecimal, for example:

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

but it also did not help.

+4
source share
4 answers

I got a solution. Just work with hex as below:

Integer.toHexString(colour);

Returns a hexadecimal string for your integer, again if you just use it

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

it will not work. You need to add a mask as

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

This solved the problem.

+6
source

Try skipping:

 mainLayout.setBackgroundColor(Color.parseColor("#FFFFFF")); 
+2
source

The question is very old. But still I found that this answer will help someone who is looking for a way to set the color as a whole.

If you look at the android documentation, the constant value for white is -1, and black is -16777216. (that is) a range of int integer color values ​​(from -1 to -16777216). Therefore, you can simply add an integer value to -16777216.

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

0
source

You can directly use the hex code. for instance

mainLayout.setBackgroundColor (# 0BB5FF);

-2
source

Source: https://habr.com/ru/post/1386104/


All Articles