Android:如何将 Spannable.setSpan 与 String.format 结合起来? [英] Android: How to combine Spannable.setSpan with String.format?
问题描述
我将 Span
设置为文本的一部分.Span 本身运行良好.但是,文本是由 Resources
中的 String.format
创建的,我不知道 start
和 end
的部分我要将 Span 设置为的文本.
I'm setting Span
to part of text. Span itself works well. However the text is created by String.format
from Resources
and I do not know start
and end
of part in the text i'm going to set Span to.
我尝试在 strings.xml
中使用自定义 HTML 标记,但 getText
或 getString
将它们删除.我可以使用这样的getString(R.string.text, "<nb>" + arg + "</nb>")
,然后Html.fromHtml()
,因为 arg
正是我想要设置跨度的地方.
I tryed to use custom HTML tags in strings.xml
, but either getText
or getString
remove them. I could use something like this getString(R.string.text, "<nb>" + arg + "</nb>")
, then Html.fromHtml()
, because the arg
is exactly where i want to set the Span.
我看到这种方法使用文本格式普通文本##span here##普通文本"
.它解析字符串,删除标签并设置 Span.
I seen this approach that used text formated "normal text ##span here## normal text"
. It parses the string removes tags and sets Span.
我的问题是,有没有更好的方法可以将 Span 设置为像 "something %s something"
这样的格式化字符串,还是应该使用上述方法之一?
My question is, is there better way to accomplish setting Span into formated string like "something %s something"
or should i use one of the above approaches?
推荐答案
我通过引入 TaggedArg
类解决了这个问题,这个类的实例扩展为
I solved this by introducing TaggedArg
class, instances of this class expands to <tag>value</tag>
. Then I created object that is responsible for reading text containing tags and replacing these tags by spans. Different spans are registered in map tag->factory.
有一个小惊喜.如果您有类似 "
的文本,Html.fromHtml
将此文本读作 "
/xx>"
.我不得不在整个文本周围添加标签 以防止这种情况发生.
There was one little surprise. If you have text like "<xx>something</xx> something"
, Html.fromHtml
reads this text as "<xx>something something</xx>"
. I had to add tags <html>
around whole text to prevent this.
这篇关于Android:如何将 Spannable.setSpan 与 String.format 结合起来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!