通过迭代失败按多个跨度样式设置文本
Set text by multiple span styles by iterating fails
我通过多个 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;
}
但是,如果我使用 'instance of' 检查跨度类型,然后创建新的构造函数,它就可以工作。为什么?
您不能多次应用同一个跨度对象。所有先前设置的跨度都将被丢弃,因此只有最后一个单词具有跨度。
如果你想重复使用它,你必须在应用它之前用CharacterStyle.wrap()
复制它:
while (matcher.find()) {
ssb.setSpan(CharacterStyle.wrap(span), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
我通过多个 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;
}
但是,如果我使用 'instance of' 检查跨度类型,然后创建新的构造函数,它就可以工作。为什么?
您不能多次应用同一个跨度对象。所有先前设置的跨度都将被丢弃,因此只有最后一个单词具有跨度。
如果你想重复使用它,你必须在应用它之前用CharacterStyle.wrap()
复制它:
while (matcher.find()) {
ssb.setSpan(CharacterStyle.wrap(span), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}