If I have a SpannedString
(or SpannableString
) like this
SpannableString spannableString = new SpannableString("Hello World!");
ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED);
BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW);
spannableString.setSpan(foregroundSpan, 1, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(backgroundSpan, 3, spannableString.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spannableString);
How would I loop through the spans of the resulting String
?
Looping through the spans in order
You can use
getSpans
to get an array of the spans in aSpanned
orSpannable
String
. However, just looping through thegetSpans
results will not necessarily give them to you in order. To get them in order you can usenextSpanTransition
.Here is an example with a
SpannedString
like the example in the question. (ASpannableString
would work the same.) The green lines show where the span transitions are. The text is black by default.The code finds the next span transition and then gets all the spans in the current range.
Output:
Thanks to this code for ideas.
Types of spans
Normally when looping through the spans you would choose a certain type of span. For example, if you wanted to remove all the foreground color spans, you could do the following:
Note that this wouldn't work with a
SpannedString
because the spans in aSpannedString
are not mutable (see this answer).If you wanted to get all the spans of any type you would set the type as
Object.class
.If you wanted all the spans that affect the appearance at the character level, you would use
CharacterStyle.class
. If within the loop you wanted to further limit the spans to those belonging toMetricAffectingSpan
, you could do it like this.Here is a general hierarchical breakdown of the span types. It may not be complete. Read Spans, a Powerful Concept for more information.