本文介绍了如何在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

  1. 使用getSpans()
  2. 获取所需类型的所有跨度
  3. 使用getSpanStart()getSpanEnd()
  4. 查找每个跨度的范围
  5. 使用removeSpan()
  6. 删除原始跨度
  7. 在与旧跨度相同的位置使用setSpan()添加新跨度类型
  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);
}

注释

  • 如果只想清除所有旧的跨度,则在创建SpannableString时使用boldString.toString().您将使用原始的boldString来获取跨度范围.
  • 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.
      • Is it possible to have multiple styles inside a TextView?
      • Looping through spans in order (explains types of spans)
      • Meaning of Span flags

      这篇关于如何在Android中将一种跨度类型更改为另一种?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-02 02:06