android - Jetpack Compose 的 TextField 中的多种颜色

标签 android kotlin android-jetpack-compose android-textinputlayout android-jetpack-compose-text

是否可以在 Jetpack Compose 的 TextField 中获得不同的颜色?
类似于 Text可与 AnnotatedString 组合使用,但 TextField 不允许 AnnotatedString作为输入值。
可组合颜色的普通文本的图像
enter image description here

最佳答案

您可以使用 VisualTransformation TextField .

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

关于android - Jetpack Compose 的 TextField 中的多种颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67517762/

相关文章:

android - Android 中的底部共享表

android - android中的camera和camera2权限

android - 您的项目包含错误,请在运行前修复它

javascript - Android 中使用 Kotlin 和 Duktape 的 JS 扩展语法

java - JodaTime:如何从 LocalTime 获取格式为 "HH:mm Z"的字符串表示形式

android - Android 上的外部键盘导致换行而不是搜索 - Kotlin

android - 记录平板电脑的屏幕和音频

javascript - Kotlin JS JSON 反序列化

android-jetpack-compose - LazyColumn 和可变列表 - 如何更新?

android - Jetpack Compose DrawImage 编译错误