由于我使用的是带有 Android Jetpack Compose 和 JetBrains Compose for Desktop 的 Kotlin Multiplatform 项目,因此我真的没有选择只能退回到 Android 的 TextView。
所以我从turbohenoch's answer 中获得灵感,并尽我所能将其扩展为能够解释多个(可能是嵌套的)HTML 格式标记。
代码肯定可以改进,它对 HTML 错误一点也不健壮,但我确实使用包含 <u> 和 <b> 标记的文本对其进行了测试,至少它可以正常工作。
代码如下:
/**
* The tags to interpret. Add tags here and in [tagToStyle].
*/
private val tags = linkedMapOf(
"<b>" to "</b>",
"<i>" to "</i>",
"<u>" to "</u>"
)
/**
* The main entry point. Call this on a String and use the result in a Text.
*/
fun String.parseHtml(): AnnotatedString {
val newlineReplace = this.replace("<br>", "\n")
return buildAnnotatedString {
recurse(newlineReplace, this)
}
}
/**
* Recurses through the given HTML String to convert it to an AnnotatedString.
*
* @param string the String to examine.
* @param to the AnnotatedString to append to.
*/
private fun recurse(string: String, to: AnnotatedString.Builder) {
//Find the opening tag that the given String starts with, if any.
val startTag = tags.keys.find { string.startsWith(it) }
//Find the closing tag that the given String starts with, if any.
val endTag = tags.values.find { string.startsWith(it) }
when {
//If the String starts with a closing tag, then pop the latest-applied
//SpanStyle and continue recursing.
tags.any { string.startsWith(it.value) } -> {
to.pop()
recurse(string.removeRange(0, endTag!!.length), to)
}
//If the String starts with an opening tag, apply the appropriate
//SpanStyle and continue recursing.
tags.any { string.startsWith(it.key) } -> {
to.pushStyle(tagToStyle(startTag!!))
recurse(string.removeRange(0, startTag.length), to)
}
//If the String doesn't start with an opening or closing tag, but does contain either,
//find the lowest index (that isn't -1/not found) for either an opening or closing tag.
//Append the text normally up until that lowest index, and then recurse starting from that index.
tags.any { string.contains(it.key) || string.contains(it.value) } -> {
val firstStart = tags.keys.map { string.indexOf(it) }.filterNot { it == -1 }.minOrNull() ?: -1
val firstEnd = tags.values.map { string.indexOf(it) }.filterNot { it == -1 }.minOrNull() ?: -1
val first = when {
firstStart == -1 -> firstEnd
firstEnd == -1 -> firstStart
else -> min(firstStart, firstEnd)
}
to.append(string.substring(0, first))
recurse(string.removeRange(0, first), to)
}
//There weren't any supported tags found in the text. Just append it all normally.
else -> {
to.append(string)
}
}
}
/**
* Get a [SpanStyle] for a given (opening) tag.
* Add your own tag styling here by adding its opening tag to
* the when clause and then instantiating the appropriate [SpanStyle].
*
* @return a [SpanStyle] for the given tag.
*/
private fun tagToStyle(tag: String): SpanStyle {
return when (tag) {
"<b>" -> {
SpanStyle(fontWeight = FontWeight.Bold)
}
"<i>" -> {
SpanStyle(fontStyle = FontStyle.Italic)
}
"<u>" -> {
SpanStyle(textDecoration = TextDecoration.Underline)
}
//This should only throw if you add a tag to the [tags] Map and forget to add it
//to this function.
else -> throw IllegalArgumentException("Tag $tag is not valid.")
}
}
我已尽力使 cmets 清楚,但这里有一个简单的解释。 tags 变量是要跟踪的标签的映射,键是开始标签,值是它们对应的结束标签。这里的任何事情也需要在tagToStyle()函数中处理,这样代码才能为每个标签获取一个合适的SpanStyle。
然后它递归地扫描输入字符串,寻找跟踪的开始和结束标签。
如果给定的字符串以结束标记开头,它将弹出最近应用的 SpanStyle(从此后附加的文本中删除它)并在删除该标记的字符串上调用递归函数。
如果给定的字符串以开始标签开头,它将推送相应的 SpanStyle(使用 tagToStyle()),然后在删除该标签的情况下调用字符串上的递归函数。
如果给定的字符串不是以结束标记或开始标记开头,但 确实 包含其中至少一个,它将找到任何跟踪标记的第一次出现(开始或关闭),通常将给定字符串中的所有文本追加到该索引,然后从它找到的第一个跟踪标记的索引开始调用字符串上的递归函数。
如果给定的字符串没有任何标签,它只会正常追加,不添加或删除任何样式。
由于我在一个正在积极开发的应用程序中使用它,我可能会根据需要继续更新它。假设没有重大变化,最新版本应该可以在其GitHub repository 上获得。