Last active
August 29, 2015 14:09
-
-
Save cab404/130c2cf0fde0ba94b90e to your computer and use it in GitHub Desktop.
Utility method for coloring text
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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