Skip to content Skip to sidebar Skip to footer

How To Reverse Priority Of Spans In A SpannableString

The priority of spans that added to a spannable affects on appearance of it in a TextView. When we add two nested Character Style to a spannable like below SpannableStringBuilder s

Solution 1:

I did for myself a little workaround. It creates new Spannable with spans reversed.

final Spannable revertSpans(Spanned stext) {
    Object[] spans = stext.getSpans(0, stext.length(), Object.class);
    Spannable ret = Spannable.Factory.getInstance().newSpannable(stext.toString());
    if (spans != null && spans.length > 0) {
        for(int i = spans.length - 1; i >= 0; --i) {
            ret.setSpan(spans[i], stext.getSpanStart(spans[i]), stext.getSpanEnd(spans[i]), stext.getSpanFlags(spans[i]));
        }
    }

    return ret;
}

Usage:

TextView tv = (TextView)finViewById(R.id.my_text_view);
Spanned stext = Html.fromHtml(text, null, myTagHandler);
Spannable sreverted = revertSpans(stext); 
tv.setText(sreverted);

Maybe this be usefull.


Post a Comment for "How To Reverse Priority Of Spans In A SpannableString"