簡體   English   中英

在 Jetpack Compose 中 Text 的最后一個單詞處添加圖標

[英]Add icon at last word of Text in Jetpack Compose

我想在最后一行的末尾顯示一個動態的多行文本和一個圖標。 這個圖標可以是動畫的。 我嘗試了一些方法,但還沒有成功。 我應該怎么做?

與我的布局有相同想法的示例視圖

在此處輸入圖像描述

Text composable 中,您可以使用inlineContent定義一個 map 標記,以替換某些文本范圍。 它用於將可組合項插入到文本布局中。
然后使用Placeholder ,您可以在文本布局中保留空間。

就像是:

val myId = "inlineContent"
val text = buildAnnotatedString {
    append("Where do you like to go?")
    // Append a placeholder string "[icon]" and attach an annotation "inlineContent" on it.
    appendInlineContent(myId, "[icon]")
}

val inlineContent = mapOf(
    Pair(
        // This tells the [CoreText] to replace the placeholder string "[icon]" by
        // the composable given in the [InlineTextContent] object.
        myId,
        InlineTextContent(
            // Placeholder tells text layout the expected size and vertical alignment of
            // children composable.
            Placeholder(
                width = 12.sp,
                height = 12.sp,
                placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
            )
        ) {
            // This Icon will fill maximum size, which is specified by the [Placeholder]
            // above. Notice the width and height in [Placeholder] are specified in TextUnit,
            // and are converted into pixel by text layout.
            
            Icon(Icons.Filled.Face,"",tint = Color.Red)
        }
    )
)

Text(text = text,
     modifier = Modifier.width(100.dp),
     inlineContent = inlineContent)

在此處輸入圖像描述

它是可組合的,因此您可以使用您最喜歡的 animation。

只是一個例子:

var blue by remember { mutableStateOf(false) }
val color by animateColorAsState(if (blue) Blue else Red,
    animationSpec = tween(
        durationMillis = 3000
    ))

並將圖標更改為

Icon(Icons.Filled.Face,"", tint = color)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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