Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How adding ImageSpan in jetpack compose Text

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)

like image 213
beigirad Avatar asked Jan 19 '26 22:01

beigirad


1 Answers

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)
like image 124
Maciej Ciemięga Avatar answered Jan 22 '26 13:01

Maciej Ciemięga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!