简体   繁体   English

在 Jetpack Compose 中 Text 的最后一个单词处添加图标

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

I want to display a dynamic multiple lines text and an icon at the end of the last line.我想在最后一行的末尾显示一个动态的多行文本和一个图标。 This icon can be animate.这个图标可以是动画的。 I try some ways but not success yet.我尝试了一些方法,但还没有成功。 How should I do?我应该怎么做?

Example view which had the same idea with my layout与我的布局有相同想法的示例视图

在此处输入图像描述

In the Text composable you can use the inlineContent to define a map of tags that replaces certain ranges of the text.Text composable 中,您可以使用inlineContent定义一个 map 标记,以替换某些文本范围。 It's used to insert composables into text layout.它用于将可组合项插入到文本布局中。
Then using a Placeholder you can reserve space in text layout.然后使用Placeholder ,您可以在文本布局中保留空间。

Something like:就像是:

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)

在此处输入图像描述

It is a composable so you can use your favorite animation.它是可组合的,因此您可以使用您最喜欢的 animation。

Just an example:只是一个例子:

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

and change the Icon to并将图标更改为

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

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM