要改变spans,您需要执行以下操作:
getSpans()
获取所需类型的所有spans。getSpanStart()
和getSpanEnd()
查找每个span的范围。removeSpan()
删除原始spans。setSpan()
添加新的span类型。这里是完成该操作的代码:
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);
}
SpannableString
时,请使用boldString.toString()
。 您将使用原始的boldString
来获取跨度范围。