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.
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.
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.
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
}
}
if you are getting colorCode in string then convert it here
public int getParseColor(String colorCode){
return Color.parseColor("#"+colorCode);
}