Skip to content

Instantly share code, notes, and snippets.

@cab404
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cab404/130c2cf0fde0ba94b90e to your computer and use it in GitHub Desktop.
Save cab404/130c2cf0fde0ba94b90e to your computer and use it in GitHub Desktop.
Utility method for coloring text
public static int indexOf(CharSequence seq, int start, char ch) {
for (int i = start; i < seq.length(); i++)
if (ch == seq.charAt(i)) return i;
return -1;
}
public static int indexOf(CharSequence seq, char ch) {
return indexOf(seq, 0, ch);
}
/**
* Recolor text according to the tags.
* <p/>
* E.g "Something red is after that:&#F00; red" will be processed and word red will be wrapped into red ColorSpan.
*/
public static Spanned colorize(CharSequence str) {
SpannableStringBuilder b = new SpannableStringBuilder(str);
Object appliedSpan = null;
int last_start = 0;
int start = 0;
while ((start = indexOf(b, '&')) != -1) {
int end;
if ((end = indexOf(b, ';')) == -1) {
b.delete(start, start + 1);
continue;
}
if (appliedSpan != null)
b.setSpan(appliedSpan, last_start, start, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
String node = b.subSequence(start + 1, end).toString();
b.delete(start, end + 1);
last_start = start;
// Here you can add your own nodes.
try {
int color = Color.parseColor(node);
appliedSpan = new ForegroundColorSpan(color);
} catch (IllegalArgumentException e) {
appliedSpan = null;
}
}
if (appliedSpan != null)
b.setSpan(appliedSpan, last_start, b.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
return b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment