本文介绍了如何在Android中将一种跨度类型更改为另一种?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在CharSequence
中采用一种类型的所有跨度,并将它们转换为另一种类型.例如,将所有粗体跨度转换为下划线跨度:
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:
我该怎么做?
(这是我今天面临的一个问题,由于我现在已经解决了这个问题,所以我在这里添加一个Q& A对.下面是我的答案.)
推荐答案
如何将跨度从一种类型更改为另一种类型
要更改跨度,您需要执行以下操作
In order change the spans, you need to do the following things
- 使用
getSpans()
获取所需类型的所有跨度 - 使用
getSpanStart()
和getSpanEnd()
查找每个跨度的范围 - 使用
removeSpan()
删除原始跨度 - 在与旧跨度相同的位置使用
setSpan()
添加新跨度类型
- 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);
}
注释
- 如果只想清除所有旧的跨度,则在创建
SpannableString
时使用boldString.toString()
.您将使用原始的boldString
来获取跨度范围. - If you want to just clear all the old spans, then use
boldString.toString()
when creating theSpannableString
. You would use the originalboldString
to get the span ranges. - Is it possible to have multiple styles inside a TextView?
- Looping through spans in order (explains types of spans)
- Meaning of Span flags
Notes
这篇关于如何在Android中将一种跨度类型更改为另一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!