通过迭代失败来设置多个跨度样式的文本

时间:2016-01-09 18:15:59

标签: android text styles spannablestring

我通过多个span样式设置了几个单词,当我将带样式的数组传递给方法时,结果只有最后一个单词具有该样式。它省略了其他的话。为什么?在我的代码和执行下面。提前谢谢。

//execution in code
charSequence = SpannableUtils.format(
        charSequence,
        new ParcelableSpan[]{new StyleSpan(Typeface.BOLD)},//or more
        new String[]{"Test1", "Test2"}
);

//method
public static CharSequence format(CharSequence charSequence, ParcelableSpan[] spans, String[] words) {
    SpannableStringBuilder ssb = new SpannableStringBuilder(charSequence);

    for (String word : words) {
        Pattern pattern = Pattern.compile(Pattern.quote(word));
        Matcher matcher = pattern.matcher(charSequence);

        for (ParcelableSpan span : spans) {
            while (matcher.find()) {
                ssb.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    return ssb;
}

但是如果我检查''实例的跨度类型然后我创建新的constructior它的工作原理。为什么呢?

1 个答案:

答案 0 :(得分:9)

您不能多次应用相同的span对象。所有先前设置的跨度都被丢弃,因此只有最后一个单词具有跨度。

如果您想重复使用它,则在应用之前必须使用CharacterStyle.wrap()进行复制:

Error 400 : Bad Request

Parameter Operation is missing