Vik*_*nko 15 android kotlin android-textinputlayout android-jetpack-compose android-compose-textfield
是否可以在 Jetpack Compose 的 TextField 中获得不同的颜色?
类似于Text
可组合 with AnnotatedString
,但 TextField 不允许AnnotatedString
作为输入值。
可与颜色组合的普通文本图像
Gab*_*tti 26
VisualTransformation
您可以在 中使用TextField
.
TextField(
value = text,
onValueChange = { text = it },
visualTransformation = ColorsTransformation()
)
Run Code Online (Sandbox Code Playgroud)
在 中,VisualTransformation
您可以使用AnnotatedString
多种样式显示文本。
就像是:
class ColorsTransformation() : VisualTransformation {
override fun filter(text: AnnotatedString): TransformedText {
return TransformedText(
buildAnnotatedStringWithColors(text.toString()),
OffsetMapping.Identity)
}
}
Run Code Online (Sandbox Code Playgroud)
和:
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()
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4955 次 |
最近记录: |