如果我有一个SpannedString(或SpannableString)
like this
SpannableString spannableString = new SpannableString("Hello World!"); ForegroundColorSpan foregroundSpan = new ForegroundColorSpan(Color.RED); BackgroundColorSpan backgroundSpan = new BackgroundColorSpan(Color.YELLOW); spannableString.setSpan(foregroundSpan,1,8,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spannableString.setSpan(backgroundSpan,3,spannableString.length() - 1,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spannableString);
如何循环生成的String的跨度?
解决方法
按顺序循环跨越
您可以使用getSpans在Spanned或Spannable String中获取跨度数组.但是,只需循环遍历getSpans结果将为not necessarily give them to you in order.为了使它们按顺序排列,您可以使用nextSpanTransition
.
下面是一个SpannedString示例,如问题中的示例. (SpannableString的工作方式相同.)绿线表示跨度转换的位置.默认情况下,文本为黑色.
int next; for (int i = 0; i < spannableString.length(); i = next) { // find the next span transition next = spannableString.nextSpanTransition(i,spannedString.length(),CharacterStyle.class); // get all spans in this range int numOfSpans = 0; CharacterStyle[] spans = spannableString.getSpans(i,next,CharacterStyle.class); for(int j = 0; j < spans.length; j++) { numOfSpans++; } Log.i("TAG","spans from " + i + " to " + next + ": " + numOfSpans); }
输出:
spans from 0 to 1: 0 spans from 1 to 3: 1 spans from 3 to 8: 2 spans from 8 to 11: 1 spans from 11 to 12: 0
感谢this code的想法.
跨度的类型
通常在循环跨越时,您会选择某种类型的跨度.例如,如果要删除所有前景颜色跨度,可以执行以下操作:
// get spans ForegroundColorSpan[] spans = spannableString.getSpans(0,spannableString.length(),ForegroundColorSpan.class); // loop through spans for (ForegroundColorSpan span : spans) { spannableString.removeSpan(span); }
请注意,这不适用于SpannedString,因为SpannedString中的跨距不可变(请参阅this answer).
如果您想获得任何类型的所有跨度,您可以将类型设置为Object.class.
Object[] spans = spannableString.getSpans(0,Object.class);
如果您想要在角色级别影响外观的所有跨度,则可以使用CharacterStyle.class.如果在循环内你想进一步限制跨度到属于MetricAffectingSpan的那些,你可以这样做.
CharacterStyle[] spans = spannableString.getSpans(0,CharacterStyle.class); for (CharacterStyle span : spans) { if (span instanceof MetricAffectingSpan) { // do something } }
以下是范围类型的一般分层细分.它可能不完整.有关更多信息,请阅读Spans,a Powerful Concept.
Object CharacterStyle BackgroundColorSpan ClickableSpan URLSpan ForegroundColorSpan MaskFilterSpan StrikethroughSpan SuggestionSpan UnderlineSpan MetricAffectingSpan AbsoluteSizeSpan LocaleSpan RelativeSizeSpan ReplacementSpan DynamicDrawableSpan ImageSpan ScaleXSpan StyleSpan SubscriptSpan SuperscriptSpan TextAppearanceSpan TypefaceSpan ParagraphStyle AlignmentSpan AlignmentSpan.Standard BulletSpan DrawableMarginSpan IconMarginSpan LeadingMarginSpan LeadingMarginSpan.LeadingMarginSpan2 LeadingMarginSpan.Standard LineBackgroundSpan LineHeightSpan LineHeightSpan.WithDensity QuoteSpan TabStopSpan TabStopSpan.Standard WrapTogetherSpan