withLink

Function

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

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

Parameters

linkA LinkAnnotation object representing a clickable part of the text
blockfunction to be executed

Returns

result of the block

Code Examples

AnnotatedStringWithHoveredLinkStylingSample

@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") }
        }
    )
}

AnnotatedStringWithLinkSample

@Composable
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")
            }
        }
    )
}

AnnotatedStringWithListenerSample

@Composable
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") }
        }
    )
}