Multiple colors in TextField of Jetpack Compose

Viewed 2283

Is it possible to get different colors in a TextField of Jetpack Compose?

Something like with the Text composable with AnnotatedString, but TextField doesn't allow AnnotatedString as input value.

Image of normal Text composable with colors

enter image description here

1 Answers

You can use the VisualTransformation in the TextField.

TextField(
    value = text,
    onValueChange = { text = it },
    visualTransformation = ColorsTransformation()
)

In the VisualTransformation you can use AnnotatedString to display the text with multiple styles.

Something like:

class ColorsTransformation() : VisualTransformation {
    override fun filter(text: AnnotatedString): TransformedText {
        return TransformedText(
            buildAnnotatedStringWithColors(text.toString()), 
            OffsetMapping.Identity)
    }
}

with:

fun buildAnnotatedStringWithColors(text:String): AnnotatedString{
    val words: List<String> = text.split("\\s+".toRegex())// splits by whitespace
    val colors = listOf(Color.Red,Color.Black,Color.Yellow,Color.Blue)
    var count = 0

    val builder = AnnotatedString.Builder()
    for (word in words) {
        builder.withStyle(style = SpanStyle(color = colors[count%4])) {
            append("$word ")
        }
        count ++
    }
    return builder.toAnnotatedString()
}

enter image description here

Related