Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set text by multiple span styles by iterating fails

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?

like image 298
deadfish Avatar asked Jan 09 '16 18:01

deadfish


Video Answer


1 Answers

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);
}
like image 189
Floern Avatar answered Oct 06 '22 00:10

Floern