appendInlineContent

Function

Common
fun AnnotatedString.Builder.appendInlineContent(
    id: String,
    alternateText: String = REPLACEMENT_CHAR,
)

Used to insert composables into the text layout. This method can be used together with the inlineContent parameter of BasicText. It will append the alternateText to this AnnotatedString and also mark this range of text to be replaced by a composable. BasicText will try to find an InlineTextContent in the map defined by inlineContent whose key equals to id, and it will use the InlineTextContent.children to replace this range of text.

Parameters

idThe id used to look up the InlineTextContent, it is referred by the inlineContent parameter of BasicText to replace the alternateText to the corresponding composable.
alternateTextThe text to be replaced by the inline content. It's displayed when the inlineContent parameter of BasicText doesn't contain id. Accessibility features will also use this text to describe the inline content.

Code Examples

InlineTextContentSample

@Composable
fun InlineTextContentSample() {
    val myId = "inlineContent"
    val text = buildAnnotatedString {
        append("Hello")
        // Append a placeholder string "[myBox]" and attach an annotation "inlineContent" on it.
        appendInlineContent(myId, "[myBox]")
    }
    val inlineContent =
        mapOf(
            Pair(
                // This tells the [BasicText] to replace the placeholder string "[myBox]" by
                // the composable given in the [InlineTextContent] object.
                myId,
                InlineTextContent(
                    // Placeholder tells text layout the expected size and vertical alignment of
                    // children composable.
                    Placeholder(
                        width = 0.5.em,
                        height = 0.5.em,
                        placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline,
                    )
                ) {
                    // This [Box] will fill maximum size, which is specified by the [Placeholder]
                    // above. Notice the width and height in [Placeholder] are specified in
                    // TextUnit,
                    // and are converted into pixel by text layout.
                    Box(modifier = Modifier.fillMaxSize().background(color = Color.Red))
                },
            )
        )
    BasicText(text = text, inlineContent = inlineContent)
}