How to set color using integer?

耗尽温柔 提交于 2020-08-02 07:38:07

问题


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.


回答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




回答2:


Try passing:

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



回答3:


The question is very old. But still I found this answer would help someone who search a way to set the color directly as 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.




回答4:


You can directly take hexadecimal code.For example

mainLayout.setBackgroundColor( #0BB5FF);



来源:https://stackoverflow.com/questions/8489990/how-to-set-color-using-integer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!