How adding ImageSpan in jetpack compose Text

9.3k Views Asked by At

As we know, AnnotatedString in JetpackCompose has provided some API of Android's SpannedString.

but I didn't find any way/workaround to inline ImageSpan to a Text (except using AndroidView)

1

There are 1 best solutions below

3
Maciej Ciemięga On BEST ANSWER

Putting images inside text can be done using AnnotatedString and inlineContent parameter of Text Composable.

  • Inside buildAnnotatedString { ... } we need to define some id for our inline content using appendInlineContent(id = ...)
  • Then in Text Composable in inlineContent parameter we provide a map matching this id to InlineTextContent() object.

You can basically put any content there as long as you can define its size up-front in Placeholder.

Here is how it looks with an Image put in the middle of the text: 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)