How to cancel span priority in SpannableString

The priority of intervals added to spannable affects its appearance in TextView. When we add two nested character styles to spannable as below

SpannableStringBuilder sp = new SpannableStringBuilder(); String blue = "blue"; String red = "red"; sp.append(blue); sp.append(red); sp.append(blue); sp.setSpan(new ForegroundColorSpan(Color.RED), blue, 2*blue, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); sp.setSpan(new ForegroundColorSpan(Color.BLUE), 0, sp.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); ((TextView)findViewById(R.id.text_view)).setText(sp); 

The order in which character styles are added is important when the text appears. Android allows you to handle the priority of flights through the Spanned.SPAN_PRIORITY flag. But when we use Html.fromHtml (), priorities are not in our hands. Can I change the priorities of the output range Html.fromHtmel or can I make them a new spannable and make new priorities span;

+4
source share
1 answer

I made a small workaround for myself. It creates a new spannable at modified intervals.

 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; } 

Using:

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

Perhaps this is helpful.

+2
source

All Articles