【问题标题】:Android Kotlin creating SpannableString from another SpannableString loses spansAndroid Kotlin 从另一个 SpannableString 创建 SpannableString 会丢失跨度
【发布时间】:2018-02-18 21:37:25
【问题描述】:

我正在创建自己的 MarkdownTextView。

在这个特定的例子中,我正在筛选一段文本,解析出斜体标签示例:

Here is text, and *here is italic text*, and maybe *more* italic text

我有一个 regex 函数 可以为我进行筛选:

(\*[^*])(.*?)([^*]\*)

以下是我使用 替换所有斜体 sn-ps 的代码

val commentBody = "Here is text, and *here is italic text*, and maybe *more* italic text"
val check = "(\*[^*])(.*?)([^*]\*)".toRegex()
val newSpan = SpannableString(commentBody.replace(check, { result ->
    val innerSpan = SpannableString(result.value.substring(1, result.value.length - 1))
    innerSpan.setSpan(StyleSpan(Typeface.ITALIC), 0, innerSpan.length, spanFlag)
    return@replace innerSpan
}))

我的正则表达式工作正常,并且

Here is text, and *here is italic text*, and maybe *more* italic text

正确转换为显示

Here is text, and here is italic text, and maybe more italic text

但是没有任何东西是斜体的。我对此进行了调试,它证实了我的恐惧,即在该转换中设置斜体跨度并使用它来设置我的新可跨度字符串时,我会丢失所有这些跨度。

有什么想法吗?

【问题讨论】:

  • 你有没有找到一个好的解决方案?

标签: android kotlin spannablestring


【解决方案1】:

如果您查看String.replace,您会发现,您返回的SpannableString 实际上用作transform: (MatchResult) -> CharSequenceCharSequence

此外,您仅从纯 String 创建外部 SpannableString

因此,您永远无法获得可用的信息。您可以查看SpannableStringBuilder 并将其与不同的方法一起使用,例如使用标记器或自定义 Markdown 跨度,它会即时删除标记语法。

【讨论】:

    【解决方案2】:

    如果有人感兴趣,这是我的答案:

    val commentBody = "Here is text, and *here is italic text*, and maybe *more* italic text"
    val check = "(\\*[^*])(.*?)([^*]\\*)".toRegex()
    val spannableStringBuilder = SpannableStringBuilder(commentBody.replace("*", ""))
    check.findAll(commentBody).map { it.value.substring(1, it.value.length - 1) }.forEach { 
        val start = spannableStringBuilder.indexOf(it)
        val end = start + it.length
        spannableStringBuilder.setSpan(StyleSpan(Typeface.ITALIC), 0, innerSpan.length, spanFlag)
    }
    return spannableStringBuilder
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      相关资源
      最近更新 更多