[英]How to change one span type to another in Android?
I would like to take all the spans of one type in a CharSequence
and convert them to a different type. 我想在CharSequence
采用一种类型的所有跨度,并将它们转换为另一种类型。 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.) (这是我今天面临的一个问题,因为我现在已经解决了这个问题,所以我在这里添加了一个问答环节。我的答案如下。)
In order change the spans, you need to do the following things 为了更改跨度,您需要执行以下操作
getSpans()
使用getSpans()
获取所需类型的所有范围 getSpanStart()
and getSpanEnd()
使用getSpanStart()
和getSpanEnd()
查找每个范围的范围 removeSpan()
使用removeSpan()
删除原始范围 setSpan()
in the same locations as the old spans 使用setSpan()
在与旧跨度相同的位置添加新跨度类型 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);
}
boldString.toString()
when creating the SpannableString
. 如果您只想清除所有旧的跨度,则在创建SpannableString
时使用boldString.toString()
。 You would use the original boldString
to get the span ranges. 您将使用原始的boldString
来获取跨度范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.