Function

withLink

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

AnnotatedStringWithLinkSample

@Composable
@Sampled
fun AnnotatedStringWithLinkSample() {
    // 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")
            }
        }
    )
}

AnnotatedStringWithHoveredLinkStylingSample

@Sampled
@Composable
fun AnnotatedStringWithHoveredLinkStylingSample() {
    // 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") }
        }
    )
}

AnnotatedStringWithListenerSample

@Composable
@Sampled
fun AnnotatedStringWithListenerSample() {
    // 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") }
        }
    )
}
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: