kotlin 从HTML标签向AnnotatedString添加换行符

iovurdzv  于 2023-08-06  发布在  Kotlin
关注(0)|答案(1)|浏览(149)

我在这里找到了一个关于突出显示HTML标签并在文本上操作它们的很好的解决方案:Android Compose: How to use HTML tags in a Text view
下面是代码中的实际解决方案:

  1. /**
  2. * Converts a [Spanned] into an [AnnotatedString] trying to keep as much formatting as possible.
  3. *
  4. * Currently supports `bold`, `italic`, `underline` and `color`.
  5. */
  6. fun Spanned.toAnnotatedString(): AnnotatedString = buildAnnotatedString {
  7. val spanned = this@toAnnotatedString
  8. append(spanned.toString())
  9. getSpans(0, spanned.length, Any::class.java).forEach { span ->
  10. val start = getSpanStart(span)
  11. val end = getSpanEnd(span)
  12. when (span) {
  13. is StyleSpan -> when (span.style) {
  14. Typeface.BOLD -> addStyle(SpanStyle(fontWeight = FontWeight.Bold), start, end)
  15. Typeface.ITALIC -> addStyle(SpanStyle(fontStyle = FontStyle.Italic), start, end)
  16. Typeface.BOLD_ITALIC -> addStyle(SpanStyle(fontWeight = FontWeight.Bold, fontStyle = FontStyle.Italic), start, end)
  17. }
  18. is UnderlineSpan -> addStyle(SpanStyle(textDecoration = TextDecoration.Underline), start, end)
  19. is ForegroundColorSpan -> addStyle(SpanStyle(color = Color(span.foregroundColor)), start, end)
  20. }
  21. }
  22. }

字符串
但我的问题是:如何改进此函数,使其也能读取换行符“\n”并执行此换行符?

kyks70gy

kyks70gy1#

尝试使用此代码

  1. @RequiresApi(Build.VERSION_CODES.N)
  2. fun htmlText(htmlText: String): AnnotatedString =
  3. Html.fromHtml(htmlText, Html.FROM_HTML_MODE_LEGACY).toAnnotatedString()

字符串

相关问题