如何在 Jetpack Compose 的文本中添加 ImageSpan

8

目前,他们没有支持它的计划。 - Phil Dukhov
1个回答

34

使用AnnotatedStringText Composable的inlineContent参数可以将图像放置在文本中。

  • buildAnnotatedString { ... }中,我们需要使用appendInlineContent(id = ...)为我们的内联内容定义一些id
  • 然后,在Text Composable中,在inlineContent参数中提供一个映射,将此idInlineTextContent()对象匹配。

基本上,您可以放置任何内容,只要您能够在Placeholder中预先定义其大小。

以下是将Image放置在文本中间的样子: enter image description here

val annotatedString = buildAnnotatedString {
    append("This is text ")
    appendInlineContent(id = "imageId")
    append(" with a call icon")
}
val inlineContentMap = mapOf(
    "imageId" to InlineTextContent(
        Placeholder(20.sp, 20.sp, PlaceholderVerticalAlign.TextCenter)
    ) {
        Image(
            imageVector = Icons.Default.Call,
            modifier = Modifier.fillMaxSize(),
            contentDescription = ""
        )
    }
)

Text(annotatedString, inlineContent = inlineContentMap)

2
这里有一个有趣的警告,你必须事先知道内容的大小。在我的情况下,我只能通过花时间预先渲染图像来弄清楚它的大小,这有点糟糕。我想知道如果我只是放入错误的大小会发生什么... - Hakanai
3
您应该将inlineContentMap放入一个remember中。 - mr.icetea
1
@mr.icetea,使用stringResource(resId)添加消息时,remember不允许使用while - Rahul Rastogi

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