我想将一种类型的所有跨度放入一个CharSequence
并将它们转换为不同的类型。例如,将所有粗体跨度转换为下划线跨度:
我该怎么做呢?
(这是我今天遇到的问题,既然我现在已经解决了,我在这里添加一个问答对。我的答案如下。)
如何将跨度从一种类型更改为另一种类型
为了更改跨度,您需要执行以下操作
- 使用以下命令获取所需类型的所有跨度
getSpans()
- 找到每个跨度的范围
getSpanStart()
and getSpanEnd()
- 删除原始跨度
removeSpan()
- 添加新的跨度类型
setSpan()
与旧跨度相同的位置
这是执行此操作的代码:
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
- 如果您只想清除所有旧的跨度,请使用
boldString.toString()
创建时SpannableString
。你会使用原来的boldString
以获得跨度范围。
See also
- TextView 中可以有多种样式吗? https://stackoverflow.com/a/41953808/3681880
- 按顺序循环遍历跨度(解释跨度的类型) https://stackoverflow.com/a/43270576/3681880
- Span 标志的含义 https://stackoverflow.com/a/41949135/3681880
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)