Skip to content

Instantly share code, notes, and snippets.

@f2prateek
Last active December 21, 2015 03:49
Show Gist options
  • Save f2prateek/6244878 to your computer and use it in GitHub Desktop.
Save f2prateek/6244878 to your computer and use it in GitHub Desktop.
FluentSpannableStringBuilder
package com.f2prateek.couchpotato.util;
import android.text.Spannable;
import android.text.SpannableString;
import java.util.ArrayList;
import java.util.List;
public class FluentSpannableStringBuilder {
List<Bean> beanList;
public FluentSpannableStringBuilder() {
beanList = new ArrayList<Bean>();
}
public void addSpan(String text, Object span) {
beanList.add(new Bean(text, span));
}
public SpannableString build() {
StringBuilder stringBuilder = new StringBuilder();
for (Bean bean : beanList) {
stringBuilder.append(bean.text);
}
SpannableString spannableString = new SpannableString(stringBuilder);
for (Bean bean : beanList) {
if (bean.span == null) {
continue;
}
int index = stringBuilder.indexOf(bean.text);
spannableString.setSpan(bean.span, index, index + bean.text.length(),
Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
return spannableString;
}
private class Bean {
String text;
Object span;
private Bean(String text, Object span) {
this.text = text;
this.span = span;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment