5

是否可以在 Jetpack Compose 的 TextField 中获得不同的颜色?

类似于Text可组合的 with AnnotatedString,但 TextField 不允许AnnotatedString作为输入值。

可组合颜色的普通文本的图像

在此处输入图像描述

4

1 回答 1

7

您可以VisualTransformationTextField.

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

在中VisualTransformation您可以使用AnnotatedString多种样式显示文本。

就像是:

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

和:

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

在此处输入图像描述

于 2021-05-15T20:13:33.007 回答