android - Jetpack Compose 的 TextField 中的多种颜色
问题描述
是否可以在 Jetpack Compose 的 TextField 中获得不同的颜色?
类似于Text
可组合的 with AnnotatedString
,但 TextField 不允许AnnotatedString
作为输入值。
可组合颜色的普通文本的图像
解决方案
您可以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()
}
推荐阅读
- angular - 在 asp.net 中构建角度部分的问题
- c - Why does my code terminate when I add a 7th character to my array?
- django - Django: production app on Heroku cant find templates with "path" urlpattern
- postgresql - 启动 pgpool 时,这个“验证失败”错误是什么?
- android - 错误:无法解决:com.android.support:appcompat-v7:28.0.0
- c# - Not receiving result it seems with "onActivityResult()"
- python - Format first row in ReportLab table
- r - 为什么使用 sf 包创建的 shapefile 在 ArcMap 中不显示相同的 CRS?
- google-apps-script - 如何防止 NOW 功能每次自动更新?有没有办法做到这一点?
- azure - DotNetNuke 实例无法启动