How to change one span type to another in Android?

半城伤御伤魂 提交于 2020-05-29 09:33:45

问题


I would like to take all the spans of one type in a CharSequence and convert them to a different type. For example, convert all the bold spans to underline spans:

How would I do that?

(This was a problem I was facing today, and since I have solved it now, I am adding a Q&A pair here. My answer is below.)


回答1:


How to change spans from one type to another

In order change the spans, you need to do the following things

  1. Get all the spans of the desired type by using getSpans()
  2. Find the range of each span with getSpanStart() and getSpanEnd()
  3. Remove the original spans with removeSpan()
  4. 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 the SpannableString. You would use the original boldString to get the span ranges.

See also

  • Is it possible to have multiple styles inside a TextView?
  • Looping through spans in order (explains types of spans)
  • Meaning of Span flags


来源:https://stackoverflow.com/questions/48569172/how-to-change-one-span-type-to-another-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!