Alternatives to ReplacementSpan in Jetpack Compose?

Viewed 514

I know this question is very vague and doesn't probably have a single correct answer. I just wanted to hear some input and create some content around advanced text styles in Compose. I hope it's fine.

Does anyone knows if there is a way to use Spans in compose? I built a custom MultiAutocompleteTextView using the Views system that created chips using ChipSpan(...): ImageSpan(...).

It looks something like this:

enter image description here

How would you handle this in Compose? Any input will be greatly appreciated! Thank you.

2 Answers

InlineTextContent might be what you are looking for. It uses AnnotatedString and placeholders and allows you to insert Composables inline with your text:

val text = buildAnnotatedString {
    appendInlineContent("chip1", "Acid")
}

val inlineContent = mapOf(
  "chip1" to InlineTextContent(
    Placeholder(
        width = 1.em, // calculate text width
        height = 1.em, // calculate text height
        placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline
    )
  ) {
     // call chip composable
  }
)

BasicText(text = text, inlineContent = inlineContent)

If you are looking to use with Text, InlineTextContent could be useful. But In case of Textfield, seems like it is yet to be implemented. Checkout the below feature request filed in issue tracker.

Related