How to change spans from one type to another

In order change the spans, you need to do the following things
- Get all the spans of the desired type by using getSpans()
- Find the range of each span with getSpanStart()andgetSpanEnd()
- Remove the original spans with removeSpan()
- Add the new span type with setSpan()in the same locations as the old spans
Here is the code to do that:
Spanned boldString = Html.fromHtml("Some <b>text</b> with <b>spans</b> in it.");
// make a spannable copy so that we can change the spans (Spanned is immutable)
SpannableString spannableString = new SpannableString(boldString);
// get all the spans of type StyleSpan since bold is StyleSpan(Typeface.BOLD)
StyleSpan[] boldSpans = spannableString.getSpans(0, spannableString.length(), StyleSpan.class);
// loop through each bold span one at a time
for (StyleSpan boldSpan : boldSpans) {
    // get the span range
    int start = spannableString.getSpanStart(boldSpan);
    int end = spannableString.getSpanEnd(boldSpan);
    // remove the bold span
    spannableString.removeSpan(boldSpan);
    // add an underline span in the same place
    UnderlineSpan underlineSpan = new UnderlineSpan();
    spannableString.setSpan(underlineSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
Notes
- If you want to just clear all the old spans, then use boldString.toString()when creating theSpannableString. You would use the originalboldStringto get the span ranges.
See also