HTML in Jetpack Compose Text
Asked Answered
E

0

5

I tried to enable HTML strings, especially with links e.g.:

"We are a <a href="/about/about_team.htm">team</a> of professionals working hard to provide free learning content."

I used it like explained here by Akram Hussain:

val body = "We are a <a href="www.link.com/about/">team</a> of professionals working hard to provide free learning content."
            val text = HtmlCompat.fromHtml(body, Html.FROM_HTML_MODE_LEGACY)
//                HtmlCompat.fromHtml(description, HtmlCompat.FROM_HTML_MODE_LEGACY)

Text(
    text = text.toString(),
    style = myStyle,
    overflow = TextOverflow.Ellipsis,
    maxLines = 4,
    modifier = Modifier
        .clickable(
            enabled = true,
            onClick = { },
            indication = rememberRipple(bounded = true),
            interactionSource = MutableInteractionSource(),
        )
        .animateContentSize(animationSpec = spring()),
    onTextLayout = {
        //
    }
)

in a androidx.compose.material.TextKt.kt Text. Unfortunately, the text is shown, but no link is highlighted and link is not working at all.

Exarchate answered 23/6, 2022 at 21:0 Comment(5)
You would need to create an AnnotatedString. Check this answerShote
@GabrieleMariotti I had a solution with ClickableText and AnnotatedString, but AnnotatedString is terrible to use. One has to track the index of the word being linked for every language. E.g. In your linked example, when the text changes, you also have to change the code val startIndex = str.indexOf("link") . I do not want to change the code (for annotedstring), prefferable it should work for all HTML out of the box. So I was looking for a solution with HTML tag like a and href, so that I do not have to use AnnotatedString anymore.Exarchate
@GabrieleMariotti Also "link" in french is "lien". The given example code would not work for french and I would have to check in my code for the correct wording in every supported language. I really do not like AnnotatedStringExarchate
Have you considered using AndroidView as shown in this answer? I think there's no built-in way in Compose so farFrondescence
gist.github.com/micHar/99d8da443bfb9fc2e92a61ebaaacba72 https://mcmap.net/q/217169/-jetpack-compose-text-hyperlink-some-section-of-the-text github.com/firefinchdev/linkify-text https://mcmap.net/q/273282/-android-compose-how-to-use-html-tags-in-a-text-view/115145Korikorie

© 2022 - 2024 — McMap. All rights reserved.