Hi guys. I'm involved in rewriting an Android app from xml/fragments to Compose and am struggling wi...
l
Hi guys. I'm involved in rewriting an Android app from xml/fragments to Compose and am struggling with one part: displaying html content. In the old version, we would do something like this:
Copy code
val html = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY)
val spannedText = SpannableString(html)
val textView = TextView(requireContext())
textView.setText(spannedText, TextView.BufferType.SPANNABLE)
And this way, the TextView will display links as blue underlined text that you can click on top open the url in a browser. I'm trying to achieve the same using Compose. I got to the following so far:
Copy code
Text(buildAnnotatedString {
    val html = Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY)
    val spannedText = SpannableString(html)
    append(spannedText)
})
This however does not display any links. It just displays as plain text. Any idea how I can achieve the same behavior from the Android TextView with Compose?
k
you could still embedd old TextView like so
Copy code
@Composable
actual fun HtmlText(html: String, modifier: Modifier, color: Color) {
    AndroidView(
        modifier = modifier,
        factory = { context -> TextView(context).apply { setTextColor(color.toArgb()) } },
        update = { it.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY) }
    )
}
l
@Kilian Thanks, I did that until now, but I also need to apply some styling to the entire with which are styles in compose
SpanStyle
. I did that with
Copy code
Text(buildAnnotatedString {
    withStyle(myComposeSpandStyle) {
    ...
    }
}
I don't think I can use that directly on a TextView but I guess I can use things like the setTextColor as in your example
j
you could use buildAnnotatedString ,set your desired style and pass it into a ClickableText composable
l
Thanks all. I think based on all the info I managed to get something working! thank you color
very nice 1