![](/img/trans.png)
[英]How to add multiple inputType in TextField Jetpack Compose
[英]Multiple colors in TextField of Jetpack Compose
你可以這樣做:
Text(buildAnnotatedString {
withStyle(style = SpanStyle(color = Color.Blue)) {
append("H")
}
append("ello ")
withStyle(style = SpanStyle(fontWeight = FontWeight.Bold, color = Color.Red)) {
append("W")
}
append("orld")
})
在文檔中查看更多信息:
https://developer.android.com/jetpack/compose/text#multiple-styles
您可以在TextField
中使用VisualTransformation
。
TextField(
value = text,
onValueChange = { text = it },
visualTransformation = ColorsTransformation()
)
在VisualTransformation
中可以使用AnnotatedString
顯示帶有多個 styles 的文本。
就像是:
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()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.