Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple colors in TextField of Jetpack Compose

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

like image 701
Viktor Isacenko Avatar asked Dec 31 '22 14:12

Viktor Isacenko


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

like image 62
Gabriele Mariotti Avatar answered Jan 07 '23 15:01

Gabriele Mariotti