Android convert color int to hexa String

If you want to convert to javascript format:

val hexColor = String.format("%06X", 0xFFFFFFFF.and(R.color.text.toColorInt(context).toLong()))

val javascriptHexColor = "#" + hexColor.substring(2) + hexColor.substring(0, 2)

Here are 2 ways to convert Integer to Hex Strings...

    int  n = 123456;
    System.out.println(String.format("#%X", n)); //use lower case x for lowercase hex
    System.out.println("#"+Integer.toHexString(n));

The answer of st0le is not correct with respect to colors. It does not work if first color components are 0. So toHexString is useless.

However this code will work as expected:

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

Tags:

Colors

Android