在Jetpack Compose中给最后一个单词添加图标

20

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

以下是一个具有与我的布局相同想法的示例视图:

输入图片说明


你只想添加图标还是想使图标动画化? - ked
2
从未需要过,但有 TextResults 的占位符。 https://developer.android.com/reference/kotlin/androidx/compose/ui/text/TextLayoutInput#placeholders() 希望这可能会对您有所帮助。如果你让它工作了,请回答你自己的问题。 - 2jan222
@ked 我都想要。 - Quyết Vũ
1个回答

42
Text 组合中,您可以使用 inlineContent 来定义标签的映射,以替换文本的某些范围。它用于将组合插入文本布局。
然后,使用 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)

输入图像描述此处

它是可组合的,因此您可以使用喜欢的动画。

仅供参考:

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)

输入图像描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接