在 Jetpack Compose 中的文本的最后一个字添加图标

Add icon at last word of Text in Jetpack Compose

我想在最后一行的末尾显示一个动态的多行文本和一个图标。该图标可以是动画的。我尝试了一些方法但还没有成功。我该怎么办?

与我的布局想法相同的示例视图

Text 可组合项中,您可以使用 inlineContent 来定义用于替换特定文本范围的标签映射。它用于将可组合项插入文本布局。
然后使用 Placeholder 您可以在文本布局中保留 space。

类似于:

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)

这是一个可组合项,因此您可以使用自己喜欢的动画。

举个例子:

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)