AnnotatedString.Builder


Builder class for AnnotatedString. Enables construction of an AnnotatedString using methods such as append and addStyle.

import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    append("Hello")
    // push green text style so that any appended text will be green
    pushStyle(SpanStyle(color = Color.Green))
    // append new text, this text will be rendered as green
    append(" World")
    // pop the green style
    pop()
    // append a string without style
    append("!")
    // then style the last added word as red, exclamation mark will be red
    addStyle(SpanStyle(color = Color.Red), "Hello World".length, this.length)

    toAnnotatedString()
}

This class implements Appendable and can be used with other APIs that don't know about AnnotatedStrings:

import androidx.compose.ui.text.buildAnnotatedString

val words = listOf("Hello", "World")
buildAnnotatedString {
    // joinTo is a Kotlin stdlib function that takes an Appendable
    words.joinTo(this, separator = " ", postfix = "!")

    toAnnotatedString()
}

Summary

Public constructors

Builder(capacity: Int)
Cmn

Create an Builder instance using the given AnnotatedString.

Cmn
Builder(text: String)

Create an Builder instance using the given String.

Cmn

Public functions

Unit
addLink(clickable: LinkAnnotation.Clickable, start: Int, end: Int)

Set a LinkAnnotation.Clickable for the given range.

Cmn
Unit
addLink(url: LinkAnnotation.Url, start: Int, end: Int)

Set a LinkAnnotation.Url for the given range.

Cmn
Unit
addStringAnnotation(tag: String, annotation: String, start: Int, end: Int)

Set an Annotation for the given range.

Cmn
Unit
addStyle(style: ParagraphStyle, start: Int, end: Int)

Set a ParagraphStyle for the given range.

Cmn
Unit
addStyle(style: SpanStyle, start: Int, end: Int)

Set a SpanStyle for the given range.

Cmn
Unit
@ExperimentalTextApi
addTtsAnnotation(ttsAnnotation: TtsAnnotation, start: Int, end: Int)

Set a TtsAnnotation for the given range.

Cmn
Unit
@ExperimentalTextApi
addUrlAnnotation(urlAnnotation: UrlAnnotation, start: Int, end: Int)

Set a UrlAnnotation for the given range.

Cmn
open AnnotatedString.Builder
append(char: Char)
Cmn
Unit

Appends the given AnnotatedString to this Builder.

Cmn
open AnnotatedString.Builder

Appends text to this Builder if non-null, and returns this Builder.

Cmn
Unit
append(text: String)

Appends the given String to this Builder.

Cmn
Unit
append(text: AnnotatedString, start: Int, end: Int)

Appends the range of text between start (inclusive) and end (exclusive) to this Builder.

Cmn
open AnnotatedString.Builder
append(text: CharSequence?, start: Int, end: Int)

Appends the range of text between start (inclusive) and end (exclusive) to this Builder if non-null, and returns this Builder.

Cmn
Unit
pop()

Ends the style or annotation that was added via a push operation before.

Cmn
Unit
pop(index: Int)

Ends the styles or annotation up to and including the pushStyle or pushStringAnnotation that returned the given index.

Cmn
Int

Attach the given LinkAnnotation to any appended text until a corresponding pop is called.

Cmn
Int
pushStringAnnotation(tag: String, annotation: String)

Attach the given annotation to any appended text until a corresponding pop is called.

Cmn
Int

Applies the given ParagraphStyle to any appended text until a corresponding pop is called.

Cmn
Int

Applies the given SpanStyle to any appended text until a corresponding pop is called.

Cmn
Int

Attach the given ttsAnnotation to any appended text until a corresponding pop is called.

Cmn
Int

Attach the given UrlAnnotation to any appended text until a corresponding pop is called.

Cmn
AnnotatedString

Constructs an AnnotatedString based on the configurations applied to the Builder.

Cmn

Public properties

Int

Returns the length of the String.

Cmn

Extension functions

inline R
<R : Any> AnnotatedString.Builder.withAnnotation(
    link: LinkAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
)

Pushes an LinkAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Cmn
inline R
@ExperimentalTextApi
<R : Any> AnnotatedString.Builder.withAnnotation(
    ttsAnnotation: TtsAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
)

Pushes an TtsAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Cmn
inline R
@ExperimentalTextApi
<R : Any> AnnotatedString.Builder.withAnnotation(
    urlAnnotation: UrlAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
)

Pushes an UrlAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Cmn
inline R
@ExperimentalTextApi
<R : Any> AnnotatedString.Builder.withAnnotation(
    tag: String,
    annotation: String,
    crossinline block: AnnotatedString.Builder.() -> R
)

Pushes an annotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Cmn
inline R
<R : Any> AnnotatedString.Builder.withStyle(
    style: ParagraphStyle,
    crossinline block: AnnotatedString.Builder.() -> R
)

Pushes style to the AnnotatedString.Builder, executes block and then pops the style.

Cmn
inline R

Pushes style to the AnnotatedString.Builder, executes block and then pops the style.

Cmn
Unit
AnnotatedString.Builder.appendInlineContent(
    id: String,
    alternateText: String
)

Used to insert composables into the text layout.

Cmn

Public constructors

Builder

Builder(capacity: Int = 16)
Parameters
capacity: Int = 16

initial capacity for the internal char buffer

Builder

Builder(text: AnnotatedString)

Create an Builder instance using the given AnnotatedString.

Builder

Builder(text: String)

Create an Builder instance using the given String.

Public functions

addLink

fun addLink(clickable: LinkAnnotation.Clickable, start: Int, end: Int): Unit

Set a LinkAnnotation.Clickable for the given range.

When clicking on the text in range, the androidx.compose.foundation.TextLinkClickHandler will be triggered with the tag corresponding to the clickable object.

Clickable link may be treated specially by screen readers, including being identified while reading text with an audio icon or being summarized in a links menu.

Parameters
clickable: LinkAnnotation.Clickable

A LinkAnnotation.Clickable object that stores the tag being linked to.

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addLink

fun addLink(url: LinkAnnotation.Url, start: Int, end: Int): Unit

Set a LinkAnnotation.Url for the given range.

When clicking on the text in range, the corresponding URL from the url annotation will be opened using androidx.compose.ui.platform.UriHandler.

URLs may be treated specially by screen readers, including being identified while reading text with an audio icon or being summarized in a links menu.

Parameters
url: LinkAnnotation.Url

A LinkAnnotation.Url object that stores the URL being linked to.

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addStringAnnotation

fun addStringAnnotation(tag: String, annotation: String, start: Int, end: Int): Unit

Set an Annotation for the given range.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    append("link: Jetpack Compose")
    // attach a string annotation that stores a URL to the text "Jetpack Compose".
    addStringAnnotation(
        tag = "URL",
        annotation = "https://developer.android.com/jetpack/compose",
        start = 6,
        end = 21
    )
}
Parameters
tag: String

the tag used to distinguish annotations

annotation: String

the string annotation that is attached

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addStyle

fun addStyle(style: ParagraphStyle, start: Int, end: Int): Unit

Set a ParagraphStyle for the given range. When a ParagraphStyle is applied to the AnnotatedString, it will be rendered as a separate paragraph.

Parameters
style: ParagraphStyle

ParagraphStyle to be applied

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addStyle

fun addStyle(style: SpanStyle, start: Int, end: Int): Unit

Set a SpanStyle for the given range.

Parameters
style: SpanStyle

SpanStyle to be applied

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addTtsAnnotation

@ExperimentalTextApi
fun addTtsAnnotation(ttsAnnotation: TtsAnnotation, start: Int, end: Int): Unit

Set a TtsAnnotation for the given range.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    append("link: Jetpack Compose")
    // attach a string annotation that stores a URL to the text "Jetpack Compose".
    addStringAnnotation(
        tag = "URL",
        annotation = "https://developer.android.com/jetpack/compose",
        start = 6,
        end = 21
    )
}
Parameters
ttsAnnotation: TtsAnnotation

an object that stores text to speech metadata that intended for the TTS engine.

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

addUrlAnnotation

@ExperimentalTextApi
fun addUrlAnnotation(urlAnnotation: UrlAnnotation, start: Int, end: Int): Unit

Set a UrlAnnotation for the given range. URLs may be treated specially by screen readers, including being identified while reading text with an audio icon or being summarized in a links menu.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    append("link: Jetpack Compose")
    // attach a string annotation that stores a URL to the text "Jetpack Compose".
    addStringAnnotation(
        tag = "URL",
        annotation = "https://developer.android.com/jetpack/compose",
        start = 6,
        end = 21
    )
}
Parameters
urlAnnotation: UrlAnnotation

A UrlAnnotation object that stores the URL being linked to.

start: Int

the inclusive starting offset of the range

end: Int

the exclusive end offset of the range

append

open fun append(char: Char): AnnotatedString.Builder

append

fun append(text: AnnotatedString): Unit

Appends the given AnnotatedString to this Builder.

Parameters
text: AnnotatedString

the text to append

append

open fun append(text: CharSequence?): AnnotatedString.Builder

Appends text to this Builder if non-null, and returns this Builder.

If text is an AnnotatedString, all spans and annotations will be copied over as well. No other subtypes of CharSequence will be treated specially. For example, any platform-specific types, such as SpannedString on Android, will only have their text copied and any other information held in the sequence, such as Android Spans, will be dropped.

append

fun append(text: String): Unit

Appends the given String to this Builder.

Parameters
text: String

the text to append

append

fun append(text: AnnotatedString, start: Int, end: Int): Unit

Appends the range of text between start (inclusive) and end (exclusive) to this Builder. All spans and annotations from text between start and end will be copied over as well.

Parameters
start: Int

The index of the first character in text to copy over (inclusive).

end: Int

The index after the last character in text to copy over (exclusive).

append

open fun append(text: CharSequence?, start: Int, end: Int): AnnotatedString.Builder

Appends the range of text between start (inclusive) and end (exclusive) to this Builder if non-null, and returns this Builder.

If text is an AnnotatedString, all spans and annotations from text between start and end will be copied over as well. No other subtypes of CharSequence will be treated specially. For example, any platform-specific types, such as SpannedString on Android, will only have their text copied and any other information held in the sequence, such as Android Spans, will be dropped.

Parameters
start: Int

The index of the first character in text to copy over (inclusive).

end: Int

The index after the last character in text to copy over (exclusive).

pop

fun pop(): Unit

Ends the style or annotation that was added via a push operation before.

pop

fun pop(index: Int): Unit

Ends the styles or annotation up to and including the pushStyle or pushStringAnnotation that returned the given index.

Parameters
index: Int

the result of the a previous pushStyle or pushStringAnnotation in order to pop to

pushLink

fun pushLink(link: LinkAnnotation): Int

Attach the given LinkAnnotation to any appended text until a corresponding pop is called.

Parameters
link: LinkAnnotation

A LinkAnnotation object that stores the URL or clickable tag being linked to.

pushStringAnnotation

fun pushStringAnnotation(tag: String, annotation: String): Int

Attach the given annotation to any appended text until a corresponding pop is called.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    // push a string annotation to be applied to any appended text after this point.
    pushStringAnnotation("ParagrapLabel", "paragraph1")
    // append a paragraph, the annotation "paragraph1" is attached
    append("Paragraph One\n")
    // pop the annotation
    pop()
    // append new paragraph
    append("Paragraph Two\n")

    toAnnotatedString()
}
Parameters
tag: String

the tag used to distinguish annotations

annotation: String

the string annotation attached on this AnnotatedString

pushStyle

fun pushStyle(style: ParagraphStyle): Int

Applies the given ParagraphStyle to any appended text until a corresponding pop is called.

import androidx.compose.ui.text.ParagraphStyle

with(AnnotatedString.Builder()) {
    // push a ParagraphStyle to be applied to any appended text after this point.
    pushStyle(ParagraphStyle(lineHeight = 18.sp))
    // append a paragraph which will have lineHeight 18.sp
    append("Paragraph One\n")
    // pop the ParagraphStyle
    pop()
    // append new paragraph, this paragraph will not have the line height defined.
    append("Paragraph Two\n")

    toAnnotatedString()
}
Parameters
style: ParagraphStyle

ParagraphStyle to be applied

pushStyle

fun pushStyle(style: SpanStyle): Int

Applies the given SpanStyle to any appended text until a corresponding pop is called.

import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    // push green text color so that any appended text will be rendered green
    pushStyle(SpanStyle(color = Color.Green))
    // append string, this text will be rendered green
    append("Hello")
    // pop the green text style
    pop()
    // append new string, this string will be default color
    append(" World")

    toAnnotatedString()
}
Parameters
style: SpanStyle

SpanStyle to be applied

pushTtsAnnotation

fun pushTtsAnnotation(ttsAnnotation: TtsAnnotation): Int

Attach the given ttsAnnotation to any appended text until a corresponding pop is called.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    // push a string annotation to be applied to any appended text after this point.
    pushStringAnnotation("ParagrapLabel", "paragraph1")
    // append a paragraph, the annotation "paragraph1" is attached
    append("Paragraph One\n")
    // pop the annotation
    pop()
    // append new paragraph
    append("Paragraph Two\n")

    toAnnotatedString()
}
Parameters
ttsAnnotation: TtsAnnotation

an object that stores text to speech metadata that intended for the TTS engine.

pushUrlAnnotation

@ExperimentalTextApi
fun pushUrlAnnotation(urlAnnotation: UrlAnnotation): Int

Attach the given UrlAnnotation to any appended text until a corresponding pop is called.

import androidx.compose.ui.text.buildAnnotatedString

buildAnnotatedString {
    // push a string annotation to be applied to any appended text after this point.
    pushStringAnnotation("ParagrapLabel", "paragraph1")
    // append a paragraph, the annotation "paragraph1" is attached
    append("Paragraph One\n")
    // pop the annotation
    pop()
    // append new paragraph
    append("Paragraph Two\n")

    toAnnotatedString()
}
Parameters
urlAnnotation: UrlAnnotation

A UrlAnnotation object that stores the URL being linked to.

toAnnotatedString

fun toAnnotatedString(): AnnotatedString

Constructs an AnnotatedString based on the configurations applied to the Builder.

Public properties

length

val lengthInt

Returns the length of the String.

Extension functions

withAnnotation

inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
    link: LinkAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
): R

Pushes an LinkAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Parameters
link: LinkAnnotation

A LinkAnnotation object that stores the URL or clic being linked to.

crossinline block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

withAnnotation

@ExperimentalTextApi
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
    ttsAnnotation: TtsAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
): R

Pushes an TtsAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Parameters
ttsAnnotation: TtsAnnotation

an object that stores text to speech metadata that intended for the TTS engine.

crossinline block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

withAnnotation

@ExperimentalTextApi
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
    urlAnnotation: UrlAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
): R

Pushes an UrlAnnotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Parameters
urlAnnotation: UrlAnnotation

A UrlAnnotation object that stores the URL being linked to.

crossinline block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

withAnnotation

@ExperimentalTextApi
inline fun <R : Any> AnnotatedString.Builder.withAnnotation(
    tag: String,
    annotation: String,
    crossinline block: AnnotatedString.Builder.() -> R
): R

Pushes an annotation to the AnnotatedString.Builder, executes block and then pops the annotation.

Parameters
tag: String

the tag used to distinguish annotations

annotation: String

the string annotation attached on this AnnotatedString

crossinline block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

withStyle

inline fun <R : Any> AnnotatedString.Builder.withStyle(
    style: ParagraphStyle,
    crossinline block: AnnotatedString.Builder.() -> R
): R

Pushes style to the AnnotatedString.Builder, executes block and then pops the style.

import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle

buildAnnotatedString {
    withStyle(SpanStyle(color = Color.Green)) {
        // green text style will be applied to all text in this block
        append("Hello")
    }
    toAnnotatedString()
}
Parameters
style: ParagraphStyle

SpanStyle to be applied

crossinline block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

See also
pushStyle
pop

withStyle

inline fun <R : Any> AnnotatedString.Builder.withStyle(style: SpanStyle, block: AnnotatedString.Builder.() -> R): R

Pushes style to the AnnotatedString.Builder, executes block and then pops the style.

import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle

buildAnnotatedString {
    withStyle(SpanStyle(color = Color.Green)) {
        // green text style will be applied to all text in this block
        append("Hello")
    }
    toAnnotatedString()
}
Parameters
style: SpanStyle

SpanStyle to be applied

block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

See also
pushStyle
pop

appendInlineContent

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

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.

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.buildAnnotatedString

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)
Parameters
id: String

The id used to look up the InlineTextContent, it is referred by the inlineContent parameter of BasicText to replace the alternateText to the corresponding composable.

alternateText: String = REPLACEMENT_CHAR

The 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.

Throws
kotlin.IllegalArgumentException

if alternateText has zero length.