【发布时间】:2014-01-23 02:03:23
【问题描述】:
假设你有以下字符串:
String s = "The cold hand reaches for the %1$s %2$s Ellesse's";
String old = "old";
String tan = "tan";
String formatted = String.format(s,old,tan); //"The cold hand reaches for the old tan Ellesse's"
假设您想以这个字符串结尾,但还为任何被String.format 替换的单词设置了一个特定的Span。
例如,我们还想做以下事情:
Spannable spannable = new SpannableString(formatted);
spannable.setSpan(new StrikethroughSpan(), oldStart, oldStart+old.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), tanStart, tanStart+tan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
是否有可靠的方法来了解old 和tan 的起始索引?
请注意,仅搜索 'old' 会返回 'cold' 中的 'old',所以这不起作用。
我猜将起作用的是事先搜索%[0-9]$s,并计算偏移量以解释String.format 中的替换。不过,这似乎很让人头疼,我怀疑可能有像String.format 这样的方法可以提供更多关于其格式细节的信息。嗯,有吗?
【问题讨论】:
-
至少对于颜色,您可以尝试替换字符串
<font color='blue'>tan</font>并使用 spannable=Html.fromHtml(formatted)。不过,<strike>old</strike>不会渲染。 -
使用TextUtils.expandTemplate 几乎可以肯定。
标签: android spannablestring spannable