Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Compose: How to use HTML tags in a Text view

I have as string from an outside source that contains HTML tags in this format: "Hello, I am <b> bold</b> text"

Before Compose I would have CDATA at the start of my HTML String, used Html.fromHtml() to convert to a Spanned and passed it to the TextView. The TextView would them have the word bold in bold.

I have tried to replicated this with Compose but I can't find the exact steps to allow me to achieve it successfully.

Any suggestions are gratefully received.

like image 661
William Avatar asked Mar 05 '21 15:03

William


People also ask

How do I change the Text color in compose?

To change color of Text composable in Android Jetpack Compose, pass a required Color value for the optional color parameter of Text composable.

How do I change font size in compose?

To change font size of Text composable in Android Jetpack Compose, pass a required font size value for the optional fontSize parameter of Text composable. Make sure to import sp , as shown in the above code snippet, when you are assign fontSize property with scale-independent pixels.


1 Answers

There is yet no official Composable to do this. For now i'm using an AndroidView with a TextView inside. Not the best solution, but it's simple and that solves the problem.

@Composable
fun HtmlText(html: String, modifier: Modifier = Modifier) {
    AndroidView(
            modifier = modifier,
            factory = { context -> TextView(context) },
            update = { it.text = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_COMPACT) }
    )
}

If you have tags in the HTML you need to set the TextView property movementMethod = LinkMovementMethod.getInstance() to make the links clickable.

like image 65
Nieto Avatar answered Sep 22 '22 04:09

Nieto