在Jetpack Compose中的文本末尾添加图标 [英] Add icon at last word of Text in Jetpack Compose

查看:21
本文介绍了在Jetpack Compose中的文本末尾添加图标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

与我的布局理念相同的示例视图

推荐答案

TextComposable中,您可以使用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)

这篇关于在Jetpack Compose中的文本末尾添加图标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆