Android convert color int to hexa String

AndroidColors

Android Problem Overview


public static int RGB(float[] hsv) {
	return Color.HSVToColor(hsv);
}

this function add an int, froma color. how can i convert that int to a hexa string: #efefef

Android Solutions


Solution 1 - Android

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);

Solution 2 - Android

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));

Solution 3 - Android

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)

Solution 4 - Android

Use this way

Java:

 String hexColor = "#" + Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))

Kotlin:

var hexColor = "#${Integer.toHexString(ContextCompat.getColor(context, R.color.colorTest))}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlacasView Question on Stackoverflow
Solution 1 - AndroidDmitry KochinView Answer on Stackoverflow
Solution 2 - Androidst0leView Answer on Stackoverflow
Solution 3 - Androidjc12View Answer on Stackoverflow
Solution 4 - AndroidRasoul MiriView Answer on Stackoverflow