I set few words by multiple span styles and when I pass array with styles to method, in the result only the last word has that styles. It ommits the other words. Why? Below my code and execution. Thank You in advance.
//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;
}
However if I check type of span with 'instance of' and then I create new constructior it works. Why?
You cannot apply the same span object multiple times. All previously set spans get discarded, thus only the last word has the span.
If you want to reuse it, you have to copy it with CharacterStyle.wrap()
before you apply it:
while (matcher.find()) {
ssb.setSpan(CharacterStyle.wrap(span), matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With