【问题标题】:Multiple colors in TextField of Jetpack ComposeJetpack Compose 的 TextField 中的多种颜色
【发布时间】:2021-05-13 10:33:45
【问题描述】:
Jetpack Compose 的 TextField 是否可以得到不同的颜色?
类似于Text 可与AnnotatedString 组合,但TextField 不允许AnnotatedString 作为输入值。
可组合颜色的普通文本图像
【问题讨论】:
标签:
android
kotlin
android-jetpack-compose
android-textinputlayout
android-jetpack-compose-text
【解决方案1】:
您可以在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()
}