user14113746
user14113746

Reputation:

is there a way to change the background color of a specific word in outlined text field jetpack compose?

I am looking for a way to change the background color of certain words in outlined text field while typing, but I couldn't find a way to achieve that yet. Does anyone know a way to do this? (Preferably in compose but other solutions are also OK.)

Upvotes: 1

Views: 2005

Answers (2)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363637

You can use the VisualTransformation property in the TextField to change the text while typing. Use an AnnotatedString to apply different SpanStyle to your text.

Something like:

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

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

In the buildAnnotatedStringWithColors you can move your logic to change the background color of certain words. It is just an example to change the color for each word.

fun buildAnnotatedStringWithColors(text:String): AnnotatedString{

    //it is just an example
    
    val words: List<String> = text.split("\\s+".toRegex())// splits by whitespace
    val builder = AnnotatedString.Builder()

    val colors = listOf(Color.Red,Color.Black,Color.Yellow,Color.Blue)
    var count = 0

    for (word in words) {
        //Use you favorite SpanStyle
        builder.withStyle(style = SpanStyle(
            background = colors[count % 4],
            color = White
        )) {
            append("$word ")
        }
        count ++
    }
    return builder.toAnnotatedString()
}

enter image description here

Upvotes: 3

Phil Dukhov
Phil Dukhov

Reputation: 87685

The simplest solution is using annotated string:

Text(buildAnnotatedString {
    append("Hello ")

    withStyle(
        style = SpanStyle(
            fontWeight = FontWeight.Bold,
            color = Color.White,
            background = Color.Blue,
        )
    ) {
        append("World")
    }
}, modifier = Modifier.padding(10.dp))

Result


Also take a look at this solution, which will allow you to use a more complex drawing like this:

Upvotes: 1

Related Questions