在Compose Text中插入图片inlineContent

914 阅读1分钟

在Android原生开发的时候,想要实现在TextView中插入图片,有多种方式可以实现:

  • 在xml文件中可以直接使用drawableEnd等属性
  • 在代码里可以使用setCompoundDrawables、setCompoundDrawablesWithIntrinsicBounds等方法
  • 使用ImageSpan定制插入图片

网上查找相关的使用资料都很多。

最近在学习使用Compose,也遇到了需要在Compose的Text里插入图片,参数看了一圈也没发现跟图片相关的,网上查找也少得可怜。

终于,发现了一线希望,有资料提及到可以使用inlineContent,Text的参数里还真有inlineContent,之前看的还是不够仔细啊。

inlineContent - a map storing composables that replaces certain ranges of the text, used to insert composables into text layout. See InlineTextContent.

意思是说可以在文本布局里指定范围用以插入composables,在Compose里那可是万物皆可composables,插入图片自然也是没问题的。

示例:

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)

在buildAnnotatedString时用以id标记,inlineContentMap里填充对应id的占位大小、对齐方式、Composable函数内容,

结果: image.png