I have String with ul and li in it. And I am trying to show them in HTML formatting in textview. textView.setText(Html.fromHtml(myHtmlText));
But tex
In my case, I'm getting a list of String (from backend as a JSON Response), then render the HTML manually using this approach for TextView only:
In Kotlin
// ViewUtils.kt
@file:JvmName("ViewUtils")
package com.company
private fun List.joinToBulletList(): String =
joinToString(prefix = "", postfix = "
", separator = "\n") {
"- $it
"
}
fun TextView.renderToHtmlWithBulletList(contents: List) {
val content = contents.joinToBulletList()
val html: Spannable = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT, null, null) as Spannable
} else {
Html.fromHtml(content, null, null) as Spannable
}
text = html
}
// AnyActivity.kt
val contents = listOf("desc 1", "desc 2", "desc 3")
textViewFromXml.renderToHtmlWithBulletList(contents)
In Java
// AnyActivity.java
List contents = new String["desc 1", "desc 2", "desc 3"];
ViewUtils.renderToHtmlWithBulletList(textViewFromXml, contents)
Notice the @file:JvmName("ViewUtils") it is useful to change the file name so Java code can call it ViewUtils.java instead of ViewUtilsKt.java. See here for more detail
P.S: Please feel free to edit this