androidx.compose.ui.text

In this page, you'll find documentation for types, properties, and functions available in the androidx.compose.ui.text package such as ParagraphStyle, TextStyle, toUpperCase, buildAnnotatedString, and substring.

If you're looking for guidance instead, check out the Text in Compose guide.

Interfaces

AnnotatedString.Annotation

Defines annotations that specify additional information to apply to ranges of text within the given AnnotatedString.

Cmn
LinkInteractionListener

An interface triggered when a user interacts with a link in the text

Cmn
Paragraph

A paragraph of text that is laid out.

Cmn
android
ParagraphIntrinsics

Calculates and presents the intrinsic width and height of text.

Cmn
TextInclusionStrategy

The text inclusion strategy used by Paragraph.getRangeForRect, it specifies when a range of text is inside the given rect based on the geometric relation between the text range's bounding box and the given rect.

Cmn

Classes

AnnotatedString

The basic data structure of text with multiple styles.

Cmn
AnnotatedString.Builder

Builder class for AnnotatedString.

Cmn
AnnotatedString.Range

The information attached on the text such as a SpanStyle.

Cmn
EmojiSupportMatch

When to replace emoji with support emoji using androidx.emoji2.

android
LinkAnnotation

An annotation that represents a clickable part of the text.

Cmn
LinkAnnotation.Clickable

An annotation that contains a clickable marked with tag.

Cmn
LinkAnnotation.Url

An annotation that contains a url string.

Cmn
MultiParagraph

Lays out and renders multiple paragraphs at once.

Cmn
MultiParagraphIntrinsics

Calculates and provides the intrinsic width and height of text that contains ParagraphStyle.

Cmn
ParagraphStyle

Paragraph styling configuration for a paragraph.

Cmn
Placeholder

A placeholder is a rectangle box inserted into text, which tells the text processor to leave an empty space.

Cmn
PlaceholderVerticalAlign

The settings used to specify how a placeholder is vertically aligned within a text line.

Cmn
PlatformParagraphStyle

Provides platform specific ParagraphStyle configuration options for styling and compatibility.

Cmn
android
PlatformSpanStyle

Provides platform specific SpanStyle configuration options for styling and compatibility.

Cmn
android
PlatformTextStyle

Provides platform specific TextStyle configuration options for styling and compatibility.

Cmn
android
SpanStyle

Styling configuration for a text span.

Cmn
StringAnnotation

An AnnotatedString.Annotation class which holds a String value.

Cmn
TextGranularity

Used by Paragraph.getRangeForRect.

Cmn
TextLayoutInput

The data class which holds the set of parameters of the text layout computation.

Cmn
TextLayoutResult

The data class which holds text layout result.

Cmn
TextLinkStyles

Represents the styles of the links in the AnnotatedString in different states

Cmn
TextMeasurer

TextMeasurer is responsible for measuring a text in its entirety so that it's ready to be drawn.

Cmn
TextRange

An immutable text range class, represents a text range from start (inclusive) to end (exclusive).

Cmn
TextStyle

Styling configuration for a Text.

Cmn
TtsAnnotation

An annotation that contains the metadata intended for text-to-speech engine.

Cmn
UrlAnnotation

This class is deprecated. Use LinkAnnotatation.Url(url) instead

Cmn
VerbatimTtsAnnotation

The text associated with this annotation is a series of characters that have to be read verbatim.

Cmn

Objects

Annotations

Top-level functions summary

AnnotatedString
AnnotatedString(text: String, paragraphStyle: ParagraphStyle)

Create an AnnotatedString with a paragraphStyle that will apply to the whole text.

Cmn
AnnotatedString
AnnotatedString(
    text: String,
    spanStyle: SpanStyle,
    paragraphStyle: ParagraphStyle?
)

Create an AnnotatedString with a spanStyle that will apply to the whole text.

Cmn
Paragraph
Paragraph(
    paragraphIntrinsics: ParagraphIntrinsics,
    constraints: Constraints,
    maxLines: Int,
    overflow: TextOverflow
)

Lays out the text in ParagraphIntrinsics with the given constraints.

Cmn
Paragraph
Paragraph(
    paragraphIntrinsics: ParagraphIntrinsics,
    maxLines: Int,
    ellipsis: Boolean,
    width: Float
)

This function is deprecated. Paragraph that takes maximum allowed width is deprecated, pass constraints instead.

Cmn
Paragraph
Paragraph(
    text: String,
    style: TextStyle,
    constraints: Constraints,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    spanStyles: List<AnnotatedString.Range<SpanStyle>>,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    maxLines: Int,
    overflow: TextOverflow
)

Lays out a given text with the given constraints.

Cmn
Paragraph
Paragraph(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>>,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    maxLines: Int,
    ellipsis: Boolean,
    width: Float,
    density: Density,
    resourceLoader: Font.ResourceLoader
)

This function is deprecated. Font.ResourceLoader is deprecated, instead pass FontFamily.Resolver

Cmn
Paragraph
Paragraph(
    text: String,
    style: TextStyle,
    width: Float,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    spanStyles: List<AnnotatedString.Range<SpanStyle>>,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    maxLines: Int,
    ellipsis: Boolean
)

This function is deprecated. Paragraph that takes maximum allowed width is deprecated, pass constraints instead.

Cmn
ParagraphIntrinsics
ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    annotations: List<AnnotatedString.Range<AnnotatedString.Annotation>>,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    placeholders: List<AnnotatedString.Range<Placeholder>>
)

Factory method to create a ParagraphIntrinsics.

Cmn
ParagraphIntrinsics
ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>>,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver
)

This function is deprecated. Use an overload that takes `annotations` instead

Cmn
ParagraphIntrinsics
ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>>,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    density: Density,
    resourceLoader: Font.ResourceLoader
)

This function is deprecated. Font.ResourceLoader is deprecated, instead use FontFamily.Resolver

Cmn
TextRange
TextRange(index: Int)

Creates a TextRange where start is equal to end, and the value of those are index.

Cmn
TextRange
TextRange(start: Int, end: Int)

An immutable text range class, represents a text range from start (inclusive) to end (exclusive).

Cmn
inline AnnotatedString

Build a new AnnotatedString by populating newly created AnnotatedString.Builder provided by builder.

Cmn
ParagraphStyle
lerp(start: ParagraphStyle, stop: ParagraphStyle, fraction: Float)

Interpolate between two ParagraphStyles.

Cmn
PlatformParagraphStyle
lerp(
    start: PlatformParagraphStyle,
    stop: PlatformParagraphStyle,
    fraction: Float
)

Interpolate between two PlatformParagraphStyle's.

Cmn
android
PlatformSpanStyle
lerp(start: PlatformSpanStyle, stop: PlatformSpanStyle, fraction: Float)

Interpolate between two PlatformSpanStyle's.

Cmn
android
SpanStyle
lerp(start: SpanStyle, stop: SpanStyle, fraction: Float)

Interpolate between two span styles.

Cmn
TextStyle
lerp(start: TextStyle, stop: TextStyle, fraction: Float)

Interpolate between two text styles.

Cmn
TextMeasurer

Creates and remembers a TextMeasurer.

Cmn
TextStyle

Fills missing values in TextStyle with default values and resolve TextDirection.

Cmn

Extension functions summary

AnnotatedString

Create capitalized AnnotatedString

Cmn
String

Returns capitalized String.

Cmn
String

Returns capitalized String.

Cmn
TextRange
TextRange.coerceIn(minimumValue: Int, maximumValue: Int)

Ensures that TextRange.start and TextRange.end values lies in the specified range minimumValue and maximumValue.

Cmn
AnnotatedString

Create capitalized AnnotatedString

Cmn
String

Returns decapitalized String.

Cmn
String

Returns decapitalized String.

Cmn
Unit
DrawScope.drawText(
    textLayoutResult: TextLayoutResult,
    brush: Brush,
    topLeft: Offset,
    alpha: Float,
    shadow: Shadow?,
    textDecoration: TextDecoration?,
    drawStyle: DrawStyle?,
    blendMode: BlendMode
)

Draw an existing text layout as produced by TextMeasurer.

Cmn
Unit
DrawScope.drawText(
    textLayoutResult: TextLayoutResult,
    color: Color,
    topLeft: Offset,
    alpha: Float,
    shadow: Shadow?,
    textDecoration: TextDecoration?,
    drawStyle: DrawStyle?,
    blendMode: BlendMode
)

Draw an existing text layout as produced by TextMeasurer.

Cmn
Unit
DrawScope.drawText(
    textMeasurer: TextMeasurer,
    text: String,
    topLeft: Offset,
    style: TextStyle,
    overflow: TextOverflow,
    softWrap: Boolean,
    maxLines: Int,
    size: Size,
    blendMode: BlendMode
)

Draw text using a TextMeasurer.

Cmn
Unit
DrawScope.drawText(
    textMeasurer: TextMeasurer,
    text: AnnotatedString,
    topLeft: Offset,
    style: TextStyle,
    overflow: TextOverflow,
    softWrap: Boolean,
    maxLines: Int,
    placeholders: List<AnnotatedString.Range<Placeholder>>,
    size: Size,
    blendMode: BlendMode
)

Draw styled text using a TextMeasurer.

Cmn
AnnotatedString
AnnotatedString.Companion.fromHtml(
    htmlString: String,
    linkStyles: TextLinkStyles?,
    linkInteractionListener: LinkInteractionListener?
)

Converts a string with HTML tags into AnnotatedString.

android
String
Cmn
AnnotatedString

Create lower case transformed AnnotatedString

Cmn
String

Returns lowercase transformed String.

Cmn
String

Returns lowercase transformed String.

Cmn
AnnotatedString

Create upper case transformed AnnotatedString

Cmn
String

Returns uppercase transformed String.

Cmn
String

Returns uppercase transformed String.

Cmn
inline R
<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
<R : Any> AnnotatedString.Builder.withAnnotation(
    urlAnnotation: UrlAnnotation,
    crossinline block: AnnotatedString.Builder.() -> R
)

This function is deprecated. Use LinkAnnotation API for links instead

Cmn
inline R
<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.withLink(
    link: LinkAnnotation,
    block: AnnotatedString.Builder.() -> R
)

Pushes a LinkAnnotation 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

Top-level functions

AnnotatedString

fun AnnotatedString(text: String, paragraphStyle: ParagraphStyle): AnnotatedString

Create an AnnotatedString with a paragraphStyle that will apply to the whole text.

Parameters
paragraphStyle: ParagraphStyle

ParagraphStyle to be applied to whole text

AnnotatedString

fun AnnotatedString(
    text: String,
    spanStyle: SpanStyle,
    paragraphStyle: ParagraphStyle? = null
): AnnotatedString

Create an AnnotatedString with a spanStyle that will apply to the whole text.

Parameters
spanStyle: SpanStyle

SpanStyle to be applied to whole text

paragraphStyle: ParagraphStyle? = null

ParagraphStyle to be applied to whole text

Paragraph

fun Paragraph(
    paragraphIntrinsics: ParagraphIntrinsics,
    constraints: Constraints,
    maxLines: Int = DefaultMaxLines,
    overflow: TextOverflow = TextOverflow.Clip
): Paragraph

Lays out the text in ParagraphIntrinsics with the given constraints. A paragraph is a text that has a single ParagraphStyle.

Parameters
paragraphIntrinsics: ParagraphIntrinsics

ParagraphIntrinsics instance

constraints: Constraints

how wide and tall the text is allowed to be. Constraints.maxWidth will define the width of the Paragraph. Constraints.maxHeight helps defining the number of lines that fit with ellipsis is true. Minimum components of the Constraints object are no-op.

maxLines: Int = DefaultMaxLines

the maximum number of lines that the text can have

overflow: TextOverflow = TextOverflow.Clip

specifies how visual overflow should be handled

Paragraph

fun Paragraph(
    paragraphIntrinsics: ParagraphIntrinsics,
    maxLines: Int = DefaultMaxLines,
    ellipsis: Boolean = false,
    width: Float
): Paragraph

Lays out the text in ParagraphIntrinsics with the given constraints. A paragraph is a text that has a single ParagraphStyle.

Parameters
paragraphIntrinsics: ParagraphIntrinsics

ParagraphIntrinsics instance

maxLines: Int = DefaultMaxLines

the maximum number of lines that the text can have

ellipsis: Boolean = false

whether to ellipsize text, applied only when maxLines is set

width: Float

how wide the text is allowed to be

Paragraph

fun Paragraph(
    text: String,
    style: TextStyle,
    constraints: Constraints,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    maxLines: Int = DefaultMaxLines,
    overflow: TextOverflow = TextOverflow.Clip
): Paragraph

Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.

If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.

Parameters
text: String

the text to be laid out

style: TextStyle

the TextStyle to be applied to the whole text

constraints: Constraints

how wide and tall the text is allowed to be. Constraints.maxWidth will define the width of the Paragraph. Constraints.maxHeight helps defining the number of lines that fit with ellipsis is true. Minimum components of the Constraints object are no-op.

density: Density

density of the device

fontFamilyResolver: FontFamily.Resolver

FontFamily.Resolver to be used to load the font given in SpanStyles

spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf()

SpanStyles to be applied to parts of text

placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()

a list of placeholder metrics which tells Paragraph where should be left blank to leave space for inline elements.

maxLines: Int = DefaultMaxLines

the maximum number of lines that the text can have

overflow: TextOverflow = TextOverflow.Clip

specifies how visual overflow should be handled

Paragraph

fun Paragraph(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    maxLines: Int = DefaultMaxLines,
    ellipsis: Boolean = false,
    width: Float,
    density: Density,
    resourceLoader: Font.ResourceLoader
): Paragraph

Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.

If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.

Parameters
text: String

the text to be laid out

style: TextStyle

the TextStyle to be applied to the whole text

spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf()

SpanStyles to be applied to parts of text

placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()

a list of placeholder metrics which tells Paragraph where should be left blank to leave space for inline elements.

maxLines: Int = DefaultMaxLines

the maximum number of lines that the text can have

ellipsis: Boolean = false

whether to ellipsize text, applied only when maxLines is set

width: Float

how wide the text is allowed to be

density: Density

density of the device

resourceLoader: Font.ResourceLoader

Font.ResourceLoader to be used to load the font given in SpanStyles

Paragraph

fun Paragraph(
    text: String,
    style: TextStyle,
    width: Float,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    maxLines: Int = DefaultMaxLines,
    ellipsis: Boolean = false
): Paragraph

Lays out a given text with the given constraints. A paragraph is a text that has a single ParagraphStyle.

If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.

Parameters
text: String

the text to be laid out

style: TextStyle

the TextStyle to be applied to the whole text

width: Float

how wide the text is allowed to be

density: Density

density of the device

fontFamilyResolver: FontFamily.Resolver

FontFamily.Resolver to be used to load the font given in SpanStyles

spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf()

SpanStyles to be applied to parts of text

placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()

a list of placeholder metrics which tells Paragraph where should be left blank to leave space for inline elements.

maxLines: Int = DefaultMaxLines

the maximum number of lines that the text can have

ellipsis: Boolean = false

whether to ellipsize text, applied only when maxLines is set

ParagraphIntrinsics

fun ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    annotations: List<AnnotatedString.Range<AnnotatedString.Annotation>>,
    density: Density,
    fontFamilyResolver: FontFamily.Resolver,
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()
): ParagraphIntrinsics

Factory method to create a ParagraphIntrinsics.

If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.

ParagraphIntrinsics

fun ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    density: Density,
    fontFamilyResolver: FontFamily.Resolver
): ParagraphIntrinsics

ParagraphIntrinsics

fun ParagraphIntrinsics(
    text: String,
    style: TextStyle,
    spanStyles: List<AnnotatedString.Range<SpanStyle>> = listOf(),
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    density: Density,
    resourceLoader: Font.ResourceLoader
): ParagraphIntrinsics

Factory method to create a ParagraphIntrinsics.

If the style does not contain any androidx.compose.ui.text.style.TextDirection, androidx.compose.ui.text.style.TextDirection.Content is used as the default value.

TextRange

fun TextRange(index: Int): TextRange

Creates a TextRange where start is equal to end, and the value of those are index.

TextRange

fun TextRange(start: Int, end: Int): TextRange

An immutable text range class, represents a text range from start (inclusive) to end (exclusive). end can be smaller than start and in those cases min and max can be used in order to fetch the values.

Parameters
start: Int

the inclusive start offset of the range. Must be non-negative, otherwise an exception will be thrown.

end: Int

the exclusive end offset of the range. Must be non-negative, otherwise an exception will be thrown.

buildAnnotatedString

inline fun buildAnnotatedString(builder: AnnotatedString.Builder.() -> Unit): AnnotatedString

Build a new AnnotatedString by populating newly created AnnotatedString.Builder provided by builder.

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

// create an AnnotatedString using the lambda builder
buildAnnotatedString {
    // append "Hello" with red text color
    withStyle(SpanStyle(color = Color.Red)) { append("Hello") }
    append(" ")
    // append "Hello" with blue text color
    withStyle(SpanStyle(color = Color.Blue)) { append("World!") }
}
Parameters
builder: AnnotatedString.Builder.() -> Unit

lambda to modify AnnotatedString.Builder

lerp

fun lerp(start: ParagraphStyle, stop: ParagraphStyle, fraction: Float): ParagraphStyle

Interpolate between two ParagraphStyles.

This will not work well if the styles don't set the same fields.

The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.

lerp

fun lerp(
    start: PlatformParagraphStyle,
    stop: PlatformParagraphStyle,
    fraction: Float
): PlatformParagraphStyle

Interpolate between two PlatformParagraphStyle's.

This will not work well if the styles don't set the same fields.

The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.

lerp

fun lerp(start: PlatformSpanStyle, stop: PlatformSpanStyle, fraction: Float): PlatformSpanStyle

Interpolate between two PlatformSpanStyle's.

This will not work well if the styles don't set the same fields.

The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.

lerp

fun lerp(start: SpanStyle, stop: SpanStyle, fraction: Float): SpanStyle

Interpolate between two span styles.

This will not work well if the styles don't set the same fields.

The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.

lerp

fun lerp(start: TextStyle, stop: TextStyle, fraction: Float): TextStyle

Interpolate between two text styles.

This will not work well if the styles don't set the same fields.

The fraction argument represents position on the timeline, with 0.0 meaning that the interpolation has not started, returning start (or something equivalent to start), 1.0 meaning that the interpolation has finished, returning stop (or something equivalent to stop), and values in between meaning that the interpolation is at the relevant point on the timeline between start and stop. The interpolation can be extrapolated beyond 0.0 and 1.0, so negative values and values greater than 1.0 are valid.

rememberTextMeasurer

@Composable
fun rememberTextMeasurer(cacheSize: Int = DefaultCacheSize): TextMeasurer

Creates and remembers a TextMeasurer. All parameters that are required for TextMeasurer except cacheSize are read from CompositionLocals. Created TextMeasurer carries an internal TextLayoutCache with cacheSize capacity. Provide 0 for cacheSize to opt-out from internal caching behavior.

Parameters
cacheSize: Int = DefaultCacheSize

Capacity of internal cache inside TextMeasurer. Size unit is the number of unique text layout inputs that are measured. Value of this parameter highly depends on the consumer use case. Provide a cache size that is in line with how many distinct text layouts are going to be calculated by this measurer repeatedly. If you are animating font attributes, or any other layout affecting input, cache can be skipped because most repeated measure calls would miss the cache.

resolveDefaults

fun resolveDefaults(style: TextStyle, direction: LayoutDirection): TextStyle

Fills missing values in TextStyle with default values and resolve TextDirection.

This function will fill all null or TextUnit.Unspecified field with actual values.

Parameters
style: TextStyle

a text style to be resolved

direction: LayoutDirection

a layout direction to be used for resolving text layout direction algorithm

Returns
TextStyle

resolved text style.

Extension functions

capitalize

fun AnnotatedString.capitalize(localeList: LocaleList = LocaleList.current): AnnotatedString

Create capitalized AnnotatedString

The capitalization sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.

Note, if the style's offset is middle of the capitalization context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.

Parameters
localeList: LocaleList = LocaleList.current

A locale list used for capitalize mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. Note that, this locale is currently ignored since underlying Kotlin method is experimental.

Returns
AnnotatedString

A capitalized string.

capitalize

fun String.capitalize(localeList: LocaleList): String

Returns capitalized String.

Parameters
localeList: LocaleList

a locale list object. If empty locale list object is passed, use current locale instead.

Returns
String

a transformed text

capitalize

fun String.capitalize(locale: Locale): String

Returns capitalized String.

Parameters
locale: Locale

a locale object

Returns
String

a transformed text

coerceIn

fun TextRange.coerceIn(minimumValue: Int, maximumValue: Int): TextRange

Ensures that TextRange.start and TextRange.end values lies in the specified range minimumValue and maximumValue. For each TextRange.start and TextRange.end values:

Parameters
minimumValue: Int

the minimum value that TextRange.start or TextRange.end can be.

maximumValue: Int

the exclusive maximum value that TextRange.start or TextRange.end can be.

decapitalize

fun AnnotatedString.decapitalize(localeList: LocaleList = LocaleList.current): AnnotatedString

Create capitalized AnnotatedString

The decapitalization sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.

Note, if the style's offset is middle of the decapitalization context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.

Parameters
localeList: LocaleList = LocaleList.current

A locale list used for decapitalize mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead. Note that, this locale is currently ignored since underlying Kotlin method is experimental.

Returns
AnnotatedString

A decapitalized string.

decapitalize

fun String.decapitalize(localeList: LocaleList): String

Returns decapitalized String.

Parameters
localeList: LocaleList

a locale list object. If empty locale list object is passed, use current locale instead.

decapitalize

fun String.decapitalize(locale: Locale): String

Returns decapitalized String.

Parameters
locale: Locale

a locale object

Returns
String

a transformed text

drawText

fun DrawScope.drawText(
    textLayoutResult: TextLayoutResult,
    brush: Brush,
    topLeft: Offset = Offset.Zero,
    alpha: Float = Float.NaN,
    shadow: Shadow? = null,
    textDecoration: TextDecoration? = null,
    drawStyle: DrawStyle? = null,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draw an existing text layout as produced by TextMeasurer.

This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.

Parameters
textLayoutResult: TextLayoutResult

Text Layout to be drawn

brush: Brush

The brush to use when drawing the text.

topLeft: Offset = Offset.Zero

Offsets the text from top left point of the current coordinate system.

alpha: Float = Float.NaN

Opacity to be applied to brush from 0.0f to 1.0f representing fully transparent to fully opaque respectively.

shadow: Shadow? = null

The shadow effect applied on the text.

textDecoration: TextDecoration? = null

The decorations to paint on the text (e.g., an underline).

drawStyle: DrawStyle? = null

Whether or not the text is stroked or filled in.

blendMode: BlendMode = DrawScope.DefaultBlendMode

Blending algorithm to be applied to the text

drawText

fun DrawScope.drawText(
    textLayoutResult: TextLayoutResult,
    color: Color = Color.Unspecified,
    topLeft: Offset = Offset.Zero,
    alpha: Float = Float.NaN,
    shadow: Shadow? = null,
    textDecoration: TextDecoration? = null,
    drawStyle: DrawStyle? = null,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draw an existing text layout as produced by TextMeasurer.

This draw function cannot relayout when async font loading resolves. If using async fonts or other dynamic text layout, you are responsible for invalidating layout on changes.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp

val textMeasurer = rememberTextMeasurer()
var textLayoutResult by remember { mutableStateOf<TextLayoutResult?>(null) }

Canvas(
    Modifier.fillMaxSize().layout { measurable, constraints ->
        val placeable = measurable.measure(constraints)
        // TextLayout can be done any time prior to its use in draw, including in a
        // background thread.
        // In this sample, text layout is measured in layout modifier. This way the layout
        // call can be restarted when async font loading completes due to the fact that
        // `.measure` call is executed in `.layout`.
        textLayoutResult =
            textMeasurer.measure(text = "Hello, World!", style = TextStyle(fontSize = 24.sp))
        layout(placeable.width, placeable.height) { placeable.placeRelative(0, 0) }
    }
) {
    // This happens during draw phase.
    textLayoutResult?.let { drawText(it) }
}
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.infiniteRepeatable
import androidx.compose.animation.core.rememberInfiniteTransition
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.LocalTextStyle
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.drawWithCache
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.layout
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints

// We can disable implicit caching since we will cache in DrawWithCache
val textMeasurer = rememberTextMeasurer(cacheSize = 0)
// Apply the current text style from theme, otherwise TextStyle.Default will be used.
val materialTextStyle = LocalTextStyle.current

// Animate color repeatedly
val infiniteTransition = rememberInfiniteTransition()
val color by
    infiniteTransition.animateColor(
        initialValue = Color.Red,
        targetValue = Color.Blue,
        animationSpec = infiniteRepeatable(tween(1000))
    )

Box(
    Modifier.fillMaxSize().drawWithCache {
        // Text layout will be measured just once until the size of the drawing area or
        // materialTextStyle changes.
        val textLayoutResult =
            textMeasurer.measure(
                text = "Hello, World!",
                style = materialTextStyle,
                constraints =
                    Constraints.fixed(
                        width = (size.width / 2).roundToInt(),
                        height = (size.height / 2).roundToInt()
                    ),
                overflow = TextOverflow.Ellipsis
            )
        // color changes will only invalidate draw phase
        onDrawWithContent {
            drawContent()
            drawText(
                textLayoutResult,
                color = color,
                topLeft =
                    Offset(
                        (size.width - textLayoutResult.size.width) / 2,
                        (size.height - textLayoutResult.size.height) / 2,
                    )
            )
        }
    }
)
Parameters
textLayoutResult: TextLayoutResult

Text Layout to be drawn

color: Color = Color.Unspecified

Text color to use

topLeft: Offset = Offset.Zero

Offsets the text from top left point of the current coordinate system.

alpha: Float = Float.NaN

opacity to be applied to the color from 0.0f to 1.0f representing fully transparent to fully opaque respectively

shadow: Shadow? = null

The shadow effect applied on the text.

textDecoration: TextDecoration? = null

The decorations to paint on the text (e.g., an underline).

drawStyle: DrawStyle? = null

Whether or not the text is stroked or filled in.

blendMode: BlendMode = DrawScope.DefaultBlendMode

Blending algorithm to be applied to the text

drawText

fun DrawScope.drawText(
    textMeasurer: TextMeasurer,
    text: String,
    topLeft: Offset = Offset.Zero,
    style: TextStyle = TextStyle.Default,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    size: Size = Size.Unspecified,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draw text using a TextMeasurer.

This draw function supports only one text style, and async font loading.

TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) { drawText(textMeasurer, "Hello, World!") }
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.sp

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) {
    drawText(
        textMeasurer = textMeasurer,
        text = "Hello, World!",
        style =
            TextStyle(
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                textDecoration = TextDecoration.Underline
            )
    )
}
Parameters
textMeasurer: TextMeasurer

Measures and lays out the text

text: String

Text to be drawn

topLeft: Offset = Offset.Zero

Offsets the text from top left point of the current coordinate system.

style: TextStyle = TextStyle.Default

the TextStyle to be applied to the text

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

size: Size = Size.Unspecified

how wide and tall the text should be. If left Size.Unspecified as its default value, text will be forced to fit inside the total drawing area from where it's placed. If size is specified, Size.width will define the width of the text. Size.height helps defining the number of lines that fit if softWrap is enabled and overflow is TextOverflow.Ellipsis. Otherwise, Size.height either defines where the text is clipped (TextOverflow.Clip) or becomes no-op.

blendMode: BlendMode = DrawScope.DefaultBlendMode

Blending algorithm to be applied to the text

drawText

fun DrawScope.drawText(
    textMeasurer: TextMeasurer,
    text: AnnotatedString,
    topLeft: Offset = Offset.Zero,
    style: TextStyle = TextStyle.Default,
    overflow: TextOverflow = TextOverflow.Clip,
    softWrap: Boolean = true,
    maxLines: Int = Int.MAX_VALUE,
    placeholders: List<AnnotatedString.Range<Placeholder>> = listOf(),
    size: Size = Size.Unspecified,
    blendMode: BlendMode = DrawScope.DefaultBlendMode
): Unit

Draw styled text using a TextMeasurer.

This draw function supports multi-styling and async font loading.

TextMeasurer carries an internal cache to optimize text layout measurement for repeated calls in draw phase. If layout affecting attributes like font size, font weight, overflow, softWrap, etc. are changed in consecutive calls to this method, TextMeasurer and its internal cache that holds layout results may not offer any benefits. Check out TextMeasurer and drawText overloads that take TextLayoutResult to learn more about text layout and draw phase optimizations.

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.ParagraphStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle

val textMeasurer = rememberTextMeasurer()

Canvas(Modifier.fillMaxSize()) {
    drawText(
        textMeasurer = textMeasurer,
        text =
            buildAnnotatedString {
                withStyle(ParagraphStyle(textAlign = TextAlign.Start)) { append("Hello") }
                withStyle(ParagraphStyle(textAlign = TextAlign.End)) { append("World") }
            }
    )
}
Parameters
textMeasurer: TextMeasurer

Measures and lays out the text

text: AnnotatedString

Text to be drawn

topLeft: Offset = Offset.Zero

Offsets the text from top left point of the current coordinate system.

style: TextStyle = TextStyle.Default

the TextStyle to be applied to the text

overflow: TextOverflow = TextOverflow.Clip

How visual overflow should be handled.

softWrap: Boolean = true

Whether the text should break at soft line breaks. If false, the glyphs in the text will be positioned as if there was unlimited horizontal space. If softWrap is false, overflow and TextAlign may have unexpected effects.

maxLines: Int = Int.MAX_VALUE

An optional maximum number of lines for the text to span, wrapping if necessary. If the text exceeds the given number of lines, it will be truncated according to overflow and softWrap. If it is not null, then it must be greater than zero.

placeholders: List<AnnotatedString.Range<Placeholder>> = listOf()

a list of Placeholders that specify ranges of text which will be skipped during layout and replaced with Placeholder. It's required that the range of each Placeholder doesn't cross paragraph boundary, otherwise IllegalArgumentException is thrown.

size: Size = Size.Unspecified

how wide and tall the text should be. If left Size.Unspecified as its default value, text will be forced to fit inside the total drawing area from where it's placed. If size is specified, Size.width will define the width of the text. Size.height helps defining the number of lines that fit if softWrap is enabled and overflow is TextOverflow.Ellipsis. Otherwise, Size.height either defines where the text is clipped (TextOverflow.Clip) or becomes no-op.

blendMode: BlendMode = DrawScope.DefaultBlendMode

Blending algorithm to be applied to the text

fromHtml

fun AnnotatedString.Companion.fromHtml(
    htmlString: String,
    linkStyles: TextLinkStyles? = null,
    linkInteractionListener: LinkInteractionListener? = null
): AnnotatedString

Converts a string with HTML tags into AnnotatedString.

If you define your string in the resources, make sure to use HTML-escaped opening brackets < instead of <.

For a list of supported tags go check Styling with HTML markup guide. Note that bullet lists are not yet available.

import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.fromHtml

// First, download a string as a plain text using one of the resources' methods. At this stage
// you will be handling plurals and formatted strings in needed. Moreover, the string will be
// resolved with respect to the current locale and available translations.
val string = stringResource(id = R.string.example)

// Next, convert a string marked with HTML tags into AnnotatedString to be displayed by Text
val styledAnnotatedString = AnnotatedString.fromHtml(htmlString = string)

BasicText(styledAnnotatedString)
Parameters
htmlString: String

HTML-tagged string to be parsed to construct AnnotatedString

linkStyles: TextLinkStyles? = null

style configuration to be applied to links present in the string in different styles

linkInteractionListener: LinkInteractionListener? = null

a listener that will be attached to links that are present in the string and triggered when user clicks on those links. When set to null, which is a default, the system will try to open the corresponding links with the androidx.compose.ui.platform.UriHandler composition local

Note that any link style passed directly to this method will be merged with the styles set directly on a HTML-tagged string. For example, if you set a color of the link via the span annotation to "red" but also pass a green color via the linkStyles, the link will be displayed as green. If, however, you pass a green background via the linkStyles instead, the link will be displayed as red on a green background.

Example of displaying styled string from resources

See also
LinkAnnotation

toLowerCase

fun AnnotatedString.toLowerCase(localeList: LocaleList = LocaleList.current): AnnotatedString

Create lower case transformed AnnotatedString

The lowercase sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.

Note, if the style's offset is middle of the lowercase mapping context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.

Parameters
localeList: LocaleList = LocaleList.current

A locale list used for lower case mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead.

Returns
AnnotatedString

A lowercase transformed string.

toLowerCase

fun String.toLowerCase(localeList: LocaleList): String

Returns lowercase transformed String.

Parameters
localeList: LocaleList

a locale list object. If empty locale list object is passed, use current locale instead.

Returns
String

a transformed text

toLowerCase

fun String.toLowerCase(locale: Locale): String

Returns lowercase transformed String.

Parameters
locale: Locale

a locale object

Returns
String

a transformed text

toUpperCase

fun AnnotatedString.toUpperCase(localeList: LocaleList = LocaleList.current): AnnotatedString

Create upper case transformed AnnotatedString

The uppercase sometimes maps different number of characters. This function adjusts the text style and paragraph style ranges to transformed offset.

Note, if the style's offset is middle of the uppercase mapping context, this function won't transform the character, e.g. style starts from between base alphabet character and accent character.

Parameters
localeList: LocaleList = LocaleList.current

A locale list used for upper case mapping. Only the first locale is effective. If empty locale list is passed, use the current locale instead.

Returns
AnnotatedString

A uppercase transformed string.

toUpperCase

fun String.toUpperCase(localeList: LocaleList): String

Returns uppercase transformed String.

Parameters
localeList: LocaleList

a locale list object. If empty locale list object is passed, use current locale instead.

Returns
String

a transformed text

toUpperCase

fun String.toUpperCase(locale: Locale): String

Returns uppercase transformed String.

Parameters
locale: Locale

a locale object

Returns
String

a transformed text

withAnnotation

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

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

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

withLink

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

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

import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withLink
import androidx.compose.ui.unit.sp

// Display a link in the text
BasicText(
    buildAnnotatedString {
        append("Build better apps faster with ")
        withLink(
            LinkAnnotation.Url(
                "https://developer.android.com/jetpack/compose",
                TextLinkStyles(style = SpanStyle(color = Color.Blue))
            )
        ) {
            append("Jetpack Compose")
        }
    }
)
import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withLink
import androidx.compose.ui.unit.sp

// Display a link in the text that gets an underline when hovered
BasicText(
    buildAnnotatedString {
        append("Build better apps faster with ")
        val link =
            LinkAnnotation.Url(
                "https://developer.android.com/jetpack/compose",
                TextLinkStyles(
                    style = SpanStyle(color = Color.Blue),
                    hoveredStyle = SpanStyle(textDecoration = TextDecoration.Underline)
                )
            )
        withLink(link) { append("Jetpack Compose") }
    }
)
import androidx.compose.foundation.text.BasicText
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withLink
import androidx.compose.ui.unit.sp

// Display a link in the text and log metrics whenever user clicks on it. In that case we handle
// the link using openUri method of the LocalUriHandler
val uriHandler = LocalUriHandler.current
BasicText(
    buildAnnotatedString {
        append("Build better apps faster with ")
        val link =
            LinkAnnotation.Url(
                "https://developer.android.com/jetpack/compose",
                TextLinkStyles(SpanStyle(color = Color.Blue))
            ) {
                val url = (it as LinkAnnotation.Url).url
                // log some metrics
                uriHandler.openUri(url)
            }
        withLink(link) { append("Jetpack Compose") }
    }
)
Parameters
link: LinkAnnotation

A LinkAnnotation object representing a clickable part of the text

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.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
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.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
style: SpanStyle

SpanStyle to be applied

block: AnnotatedString.Builder.() -> R

function to be executed

Returns
R

result of the block

See also
pushStyle
pop