有没有办法更改轮廓文本字段 Jetpack Compose 中特定单词的背景颜色?

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

我正在寻找一种方法来在打字时更改轮廓文本字段中某些单词的背景颜色,但我还没有找到实现它的方法。有谁知道这样做的方法吗? (最好在 compose 中,但其他解决方案也可以。)

最简单的解决方案是使用带注释的字符串:

Text(buildAnnotatedString {
    append("Hello ")

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

结果


另请参阅 ,这将允许您使用更复杂的绘图,如下所示:

您可以在 TextField 中使用 VisualTransformation 属性 在键入时更改文本。使用 AnnotatedString 将不同的 SpanStyle 应用到您的文本。

类似于:

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

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

buildAnnotatedStringWithColors中你可以移动你的逻辑来改变某些单词的背景颜色。每个字改变颜色只是一个例子。

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()
}