簡體   English   中英

Jetpack Compose的TextField中的多個colors

[英]Multiple colors in TextField of Jetpack Compose

是否可以在 Jetpack Compose 的 TextField 中獲得不同的 colors?

類似於Text可與AnnotatedString組合的東西,但 TextField 不允許AnnotatedString作為輸入值。

可與 colors 組合的普通文本的圖像

在此處輸入圖像描述

你可以這樣做:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM