Jetpack Compose中TextField的多个颜色

15

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

就像使用AnnotatedStringText可组合项一样,但是TextField不允许将AnnotatedString作为输入值。

带有颜色的普通文本合成图像

输入图片描述

3个回答

25
您可以在TextField中使用VisualTransformation
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()
}

enter image description here


1
非常感谢,这正是我所需要的。 <3 - Viktor Isacenko
有没有办法在删除字符时删除整个带样式的单词。我有一些带颜色的样式文本。这些是@提到的名字。想要删除整个名字。有什么办法可以做到吗? - Raghunandan

0
根据Gabriele Mariotti的回答,如果您在继承VisualTransformation类时遇到问题,可以直接在TextField中使用TransformedText。
TextField(
    value = text,
    onValueChange = { text = it },
    visualTransformation = {
        TransformedText(
            buildAnnotatedStringWithColors(text),
            OffsetMapping.Identity
        )
    }
)


fun buildAnnotatedStringWithColors(text:String): AnnotatedString{ ... }

0

如果您使用使用TextFieldValue而不是普通字符串的版本(请参见docs),则TextField直接支持AnnotatedString。

注释字符串包含在TextFieldValue中的annotatedString属性中(请参见docs),与选择和组合范围一起。

更新:存在一个已知问题,当TextField获得焦点时会使格式信息丢失,因此暂时不要使用这种方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接