如何在同一部分文本上的TextView的文本上设置多个跨度?

假设我有下一个文本:

你好,stackOverflow

我希望将第二个单词设置为RelativeSizeSpan (设置相对字体大小)和TextAppearanceSpan (设置文本的颜色),如何合并它们两个?

我所知道的是,我可以select其中之一,例如使用下面的代码:

final SpannableString textToShow = new SpannableString("Hello stackOverflow"); textToShow.setSpan(new RelativeSizeSpan(1.5f), textToShow.length() - "stackOverflow".length(),textToShow.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(textToShow); 

但是我还需要设置颜色,甚至添加其他生成类的其他function。

我能做什么 ?

Solutions Collecting From Web of "如何在同一部分文本上的TextView的文本上设置多个跨度?"

只需设置其他跨度。 必要时他们将重叠/合并。 这段代码适用于我:

 final SpannableString text = new SpannableString("Hello stackOverflow"); text.setSpan(new RelativeSizeSpan(1.5f), text.length() - "stackOverflow".length(), text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); text.setSpan(new ForegroundColorSpan(Color.RED), 3, text.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tv.setText(text); 

我知道这是对已经回答的问题的一个新答复,但是我想分享一个我做的实用工具类,这使得这个任务更容易。

 public class SimpleSpanBuilder { private class SpanSection{ private final String text; private final int startIndex; private final CharacterStyle[] styles; private SpanSection(String text, int startIndex,CharacterStyle... styles){ this.styles = styles; this.text = text; this.startIndex = startIndex; } private void apply(SpannableStringBuilder spanStringBuilder){ if (spanStringBuilder == null) return; for (CharacterStyle style : styles){ spanStringBuilder.setSpan(style, startIndex, startIndex + text.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); } } } private List<SpanSection> spanSections; private StringBuilder stringBuilder; public SimpleSpanBuilder(){ stringBuilder = new StringBuilder(); spanSections = new ArrayList<>(); } public SimpleSpanBuilder append(String text,CharacterStyle... styles){ if (styles != null && styles.length > 0) { spanSections.add(new SpanSection(text, stringBuilder.length(),styles)); } stringBuilder.append(text); return this; } public SimpleSpanBuilder appendWithSpace(String text,CharacterStyle... styles){ return append(text.concat(" "),styles); } public SimpleSpanBuilder appendWithLineBreak(String text,CharacterStyle... styles){ return append(text.concat("\n"),styles); } public SpannableStringBuilder build(){ SpannableStringBuilder ssb = new SpannableStringBuilder(stringBuilder.toString()); for (SpanSection section : spanSections){ section.apply(ssb); } return ssb; } @Override public String toString() { return stringBuilder.toString(); } } 

用法:

 SimpleSpanBuilder ssb = new SimpleSpanBuilder(); ssb.appendWithSpace("Hello"); ssb.append("StackOverflow",new ForegroundColorSpan(Color.RED),new RelativeSizeSpan(1.5)); textView.setText(ssb.build());