4
votes

I have a string that contains html, how can I display this in a Jetpack compose Text?

In a TextView I would use a Spanned and do something like:

TextView.setText(Html.fromHtml("<p>something", HtmlCompat.FROM_HTML_MODE_LEGACY)

How can I do this with Text from Jetpack compose?

3
You would need to create an AnnotatedString. I am not aware of any existing HTML->AnnotatedString converter libraries at this time, though I am sure that somebody will eventually create one.CommonsWare
Maybe this library can suit your needs.Emmanuel Guerra

3 Answers

2
votes

Same answer as Yhondri, but using HtmlCompat if you are targeting api >24:

@Composable
fun Html(text: String) {
    AndroidView(factory = { context ->
        TextView(context).apply {
            setText(HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_MODE_LEGACY))
        }
    })
}
1
votes

Unfortunately, Jetpack compose does NOT support HTML yet...

So, what you could do is:

Option 1: Create your own HTML parser

Jetpack compose supports basic styling such as Bold, color, font etc.. So what you can do is loop through the original HTML text and apply text style manually.

Option 2: Integrate the old TextView into your Jetpack compose.

Please read: Adopting Compose in your app

Thanks.

1
votes

You can integrate the old TextView into your Jetpack compose like follows:

AndroidView(factory = { context ->
                    TextView(context).apply {
                        text = Html.fromHtml(your_html)
                    }
                })

More info: https://foso.github.io/Jetpack-Compose-Playground/viewinterop/androidview/