Skip to content

Instantly share code, notes, and snippets.

@cab404 cab404/colorize.java
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.