Class

SpanStyle

Styling configuration that applies at the character level.

SpanStyleSample

@Sampled
@Composable
fun SpanStyleSample() {
    Text(
        fontSize = 16.sp,
        text =
            buildAnnotatedString {
                withStyle(style = SpanStyle(color = Color.Red)) { append("Hello") }
                withStyle(SpanStyle(color = Color.Blue)) { append(" World") }
            },
    )
}

SpanStyleBrushSample

@Sampled
@Composable
fun SpanStyleBrushSample() {
    val brushColors = listOf(Color.Red, Color.Blue, Color.Green, Color.Yellow)
    Text(
        fontSize = 16.sp,
        text =
            buildAnnotatedString {
                withStyle(SpanStyle(brush = Brush.radialGradient(brushColors))) { append("Hello") }
                withStyle(SpanStyle(brush = Brush.radialGradient(brushColors.asReversed()))) {
                    append(" World")
                }
            },
    )
}

AnnotatedStringBuilderSample

@Sampled
fun AnnotatedStringBuilderSample() {
    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()
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: