0

Color.parseColor("#444444") works as expected. However, ... Color.parseColor("#444") throws the Exception.

Is there a built-in way for smarter color parsing? Unfortunately, I'm getting them in different formats from Backend.

jakub
  • 3,576
  • 3
  • 29
  • 55
  • Does this post help you https://stackoverflow.com/questions/6539879/how-to-convert-a-color-integer-to-a-hex-string-in-android – Prashant.J Apr 16 '20 at 12:19
  • Unfortunately not, I'm looking for a way to convert String -> Int. And accept string colors in various formats – jakub Apr 16 '20 at 12:20
  • 1
    Check this one, please https://stackoverflow.com/questions/5248583/how-to-get-a-color-from-hexadecimal-color-string – Ajay Thakur Apr 16 '20 at 12:23

3 Answers3

1

According to w3_spec for a 3 digits hex color you just need to duplicate each value, something like this

#F3A -> #FF33AA

since you are getting the value from backend you could try to apply a regex to convert the value before the Color.parseColor like this(written in Kotlin)

val color = "#FA3"
var colorConverted = color.replace("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])".toRegex(), "#$1$1$2$2$3$3")

Here's the link to the playground, hope it helps.

0

Thank you @Alejandro_rios. I' ve written extension based on your answer

@ColorInt
fun String.toColor(): Int {
    val colorString = if(this.length == 4) {
        replace("#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])".toRegex(), "#$1$1$2$2$3$3")
    } else {
        this
    }

    return try {
        colorString.toColorInt()
    } catch (e: Exception) {
        Timber.d("Error parsing color: $this, e.message = ${e.message}")
        Color.BLACK
    }
}
jakub
  • 3,576
  • 3
  • 29
  • 55
-1

if you are getting colorCode in string then convert it here

 public int getParseColor(String colorCode){
        return Color.parseColor("#"+colorCode);
    }
Wahdat Jan
  • 3,988
  • 3
  • 21
  • 46