{% setvar book_path %}/reference/androidx/_book.yaml{% endsetvar %} {% include "_shared/_reference-head-tags.html" %}

AnnotatedString.Builder

public final class AnnotatedString.Builder


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

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
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.AnnotatedString
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(int capacity)

Create an Builder instance using the given AnnotatedString.

Create an Builder instance using the given String.

Public methods

final void
addStringAnnotation(
    @NonNull String tag,
    @NonNull String annotation,
    int start,
    int end
)

Set an Annotation for the given range.

final void
addStyle(@NonNull ParagraphStyle style, int start, int end)

Set a ParagraphStyle for the given range.

final void
addStyle(@NonNull SpanStyle style, int start, int end)

Set a SpanStyle for the given range.

final void
@ExperimentalTextApi
addTtsAnnotation(@NonNull TtsAnnotation ttsAnnotation, int start, int end)

Set a TtsAnnotation for the given range.

final void
@ExperimentalTextApi
addUrlAnnotation(@NonNull UrlAnnotation urlAnnotation, int start, int end)

Set a UrlAnnotation for the given range.

@NonNull AnnotatedString.Builder
append(char char)
final void

Appends the given AnnotatedString to this Builder.

@NonNull AnnotatedString.Builder

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

final void

Appends the given String to this Builder.

final void
append(@NonNull AnnotatedString text, int start, int end)

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

@NonNull AnnotatedString.Builder
append(CharSequence text, int start, int end)

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

final int

Returns the length of the String.

final void
pop()

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

final void
pop(int index)

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

final int

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

final int

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

final int

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

final int

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

final int

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

final @NonNull AnnotatedString

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

Extension functions

final @NonNull R

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

final @NonNull R

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

final @NonNull R

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

final @NonNull R

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

final @NonNull R

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

final void
InlineTextContentKt.appendInlineContent(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull String id,
    @NonNull String alternateText
)

Used to insert composables into the text layout.

Public constructors

Builder

public Builder(int capacity)
Parameters
int capacity

initial capacity for the internal char buffer

Builder

public Builder(@NonNull AnnotatedString text)

Create an Builder instance using the given AnnotatedString.

Builder

public Builder(@NonNull String text)

Create an Builder instance using the given String.

Public methods

addStringAnnotation

public final void addStringAnnotation(
    @NonNull String tag,
    @NonNull String annotation,
    int start,
    int end
)

Set an Annotation for the given range.

import androidx.compose.ui.text.AnnotatedString
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
@NonNull String tag

the tag used to distinguish annotations

@NonNull String annotation

the string annotation that is attached

int start

the inclusive starting offset of the range

int end

the exclusive end offset of the range

addStyle

public final void addStyle(@NonNull ParagraphStyle style, int start, int end)

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

Parameters
@NonNull ParagraphStyle style

ParagraphStyle to be applied

int start

the inclusive starting offset of the range

int end

the exclusive end offset of the range

addStyle

public final void addStyle(@NonNull SpanStyle style, int start, int end)

Set a SpanStyle for the given range.

Parameters
@NonNull SpanStyle style

SpanStyle to be applied

int start

the inclusive starting offset of the range

int end

the exclusive end offset of the range

addTtsAnnotation

@ExperimentalTextApi
public final void addTtsAnnotation(@NonNull TtsAnnotation ttsAnnotation, int start, int end)

Set a TtsAnnotation for the given range.

import androidx.compose.ui.text.AnnotatedString
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
@NonNull TtsAnnotation ttsAnnotation

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

int start

the inclusive starting offset of the range

int end

the exclusive end offset of the range

addUrlAnnotation

@ExperimentalTextApi
public final void addUrlAnnotation(@NonNull UrlAnnotation urlAnnotation, int start, int end)

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.AnnotatedString
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
@NonNull UrlAnnotation urlAnnotation

A UrlAnnotation object that stores the URL being linked to.

int start

the inclusive starting offset of the range

int end

the exclusive end offset of the range

append

public @NonNull AnnotatedString.Builder append(char char)

append

public final void append(@NonNull AnnotatedString text)

Appends the given AnnotatedString to this Builder.

Parameters
@NonNull AnnotatedString text

the text to append

append

public @NonNull AnnotatedString.Builder append(CharSequence text)

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

public final void append(@NonNull String text)

Appends the given String to this Builder.

Parameters
@NonNull String text

the text to append

append

public final void append(@NonNull AnnotatedString text, int start, int end)

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
int start

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

int end

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

append

public @NonNull AnnotatedString.Builder append(CharSequence text, int start, int end)

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
int start

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

int end

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

getLength

public final int getLength()

Returns the length of the String.

pop

public final void pop()

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

pop

public final void pop(int index)

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

Parameters
int index

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

pushStringAnnotation

public final int pushStringAnnotation(@NonNull String tag, @NonNull String annotation)

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

import androidx.compose.ui.text.AnnotatedString
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
@NonNull String tag

the tag used to distinguish annotations

@NonNull String annotation

the string annotation attached on this AnnotatedString

pushStyle

public final int pushStyle(@NonNull ParagraphStyle style)

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

import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.unit.sp

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
@NonNull ParagraphStyle style

ParagraphStyle to be applied

pushStyle

public final int pushStyle(@NonNull SpanStyle style)

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

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
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
@NonNull SpanStyle style

SpanStyle to be applied

pushTtsAnnotation

public final int pushTtsAnnotation(@NonNull TtsAnnotation ttsAnnotation)

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

import androidx.compose.ui.text.AnnotatedString
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
@NonNull TtsAnnotation ttsAnnotation

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

pushUrlAnnotation

@ExperimentalTextApi
public final int pushUrlAnnotation(@NonNull UrlAnnotation urlAnnotation)

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

import androidx.compose.ui.text.AnnotatedString
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
@NonNull UrlAnnotation urlAnnotation

A UrlAnnotation object that stores the URL being linked to.

toAnnotatedString

public final @NonNull AnnotatedString toAnnotatedString()

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

Extension functions

AnnotatedStringKt.withAnnotation

@ExperimentalTextApi
public final @NonNull R <R extends Object> AnnotatedStringKt.withAnnotation(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull TtsAnnotation ttsAnnotation,
    @ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block
)

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

Parameters
@NonNull TtsAnnotation ttsAnnotation

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

@ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block

function to be executed

Returns
@NonNull R

result of the block

AnnotatedStringKt.withAnnotation

@ExperimentalTextApi
public final @NonNull R <R extends Object> AnnotatedStringKt.withAnnotation(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull UrlAnnotation urlAnnotation,
    @ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block
)

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

Parameters
@NonNull UrlAnnotation urlAnnotation

A UrlAnnotation object that stores the URL being linked to.

@ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block

function to be executed

Returns
@NonNull R

result of the block

AnnotatedStringKt.withAnnotation

@ExperimentalTextApi
public final @NonNull R <R extends Object> AnnotatedStringKt.withAnnotation(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull String tag,
    @NonNull String annotation,
    @ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block
)

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

Parameters
@NonNull String tag

the tag used to distinguish annotations

@NonNull String annotation

the string annotation attached on this AnnotatedString

@ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block

function to be executed

Returns
@NonNull R

result of the block

AnnotatedStringKt.withStyle

public final @NonNull R <R extends Object> AnnotatedStringKt.withStyle(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull ParagraphStyle style,
    @ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block
)

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

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
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
@NonNull ParagraphStyle style

SpanStyle to be applied

@ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block

function to be executed

Returns
@NonNull R

result of the block

See also
pushStyle
pop

AnnotatedStringKt.withStyle

public final @NonNull R <R extends Object> AnnotatedStringKt.withStyle(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull SpanStyle style,
    @ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block
)

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

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
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
@NonNull SpanStyle style

SpanStyle to be applied

@ExtensionFunctionType @NonNull Function1<@NonNull AnnotatedString.Builder, @NonNull R> block

function to be executed

Returns
@NonNull R

result of the block

See also
pushStyle
pop

InlineTextContentKt.appendInlineContent

public final void InlineTextContentKt.appendInlineContent(
    @NonNull AnnotatedString.Builder receiver,
    @NonNull String id,
    @NonNull String alternateText
)

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.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.unit.em

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
@NonNull String id

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.

@NonNull String alternateText

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.