如何以编程方式向字符串添加注释标签

问题描述

this video 中,Google 给出了基于 Annotation 标签格式化 String 部分的示例,该标签可用于在 String 中设置键/值对strings.xml

这是一个例子:

strings.xml

<string name="test">Hello <annotation font="sans-serif-medium">World!</annotation></string>

科特林代码

val spannedString = getText(R.string.title) as SpannedString
val annotations = spannedString.getSpans(0,spannedString.length,Annotation::class.java)
for (annotation in annotations) {
    if (annotation.key == "font") {
        val fontName = annotation.value
        val typeFace: Typeface = ...
        spannable.setSpan(TypefaceSpan(typeFace),abstract.getSpanStart(annotation),abstract.getSpanEnd(annotation),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
}

这也与 ReplacementSpan 中的 this article 一起使用,以解决 ReplacementSpans 无法流入下一行文本的问题。

我的问题是:

我需要动态创建/删除注释标签,以便我可以以编程方式从标记有注释标签的文本部分中删除标签,或将标签添加到未带注释的文本中。

我怎样才能做到这一点?

解决方法

通常我们将 String 跨度与 ParcelableSpan 的实现附加在一起,例如 ForegroundColorSpanBackgroundColorSpanUnderlineSpanTypefaceSpan .. 等>

通过观察 Annotation 也实现了 ParcelableSpan,我们可以使用 setSpan() 为其附加注释,并将键/值对添加到 its constructor .

我的另一个观察是 setSpan() 实际上接受一个 Object 作为第一个参数。

所以参考引用的问题article示例(GitHub Repo);以编程方式设置注释:

val span = SpannableString("value \n 1 Some Value Value 2")
span.setSpan(Annotation("","rounded"),10,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
span.setSpan(Annotation("",15,19,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

textView.text = span

Annotation 的键在本例中无关紧要,因为我们只需要它的标签/值。所以将其保留为空字符串。

结果:

enter image description here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...