androidandroid-jetpack-composeandroid-jetpack-compose-text

Jetpack Compose Text hyperlink some section of the text


How can i add hyperlink to some section of the text of Text component?

With buildAnnotatedString i can set link section blue and underlined as in image below, but how can i also turn that section into link?

enter image description here

   val annotatedLinkString = buildAnnotatedString {
        val str = "Click this link to go to web site"
        val startIndex = str.indexOf("link")
        val endIndex = startIndex + 4
        append(str)
        addStyle(
            style = SpanStyle(
                color = Color(0xff64B5F6),
                textDecoration = TextDecoration.Underline
            ), start = startIndex, end = endIndex
        )
    }

    Text(
        modifier = modifier
            .padding(16.dp)
            .fillMaxWidth(),
        text = annotatedLinkString
    )

I can also get Spanned but is there any way to use it with Text?

val str: Spanned = HtmlCompat.fromHtml(
    "<a href=\"http://www.github.com\">Github</a>", HtmlCompat.FROM_HTML_MODE_LEGACY
)

Solution

  • How can i add hyperlink to some section of the text of Text component?

    with(AnnotatedString.Builder()) {
        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
        )
    }
    

    tag:The tag used to distinguish annotations

    annotation: The string annotation that is attached

    start: The inclusive starting offset of the range

    end: The exclusive end offset of the

    Source