Christian Christian - 4 months ago 8x
Android Question

Coloring part of the text in an android TextView with a color defined in an xml file

I have text that I load from an external source. I can control how the external source defines the string.

text = "foo<font color='red'>bar</font>foo"
text2 = "foofoo<font color='red'>bar</font>foo"

Is there a way to specify that Android isn't supposed to use the standard CSS color red but the red I define in my

I want to call
and then have my TextView with the correct color.


I solved my problem myself with regex:

public static Spanned formatTextForTextView(String text, Context context){
    text = replaceColorForHex(text, "blue",, context);
    text = replaceColorForHex(text, "green",, context);
    text = replaceColorForHex(text, "red",, context);
    return Html.fromHtml(text);

private static String replaceColorForHex(
    String text,
    String colorString,
    int colorId,
    Context context
    String colorHex = getColorHex(colorId, context);

    Pattern pattern = Pattern.compile(
        "(<font[^>]+color=)(['" + '"' + "]"
            + colorString
            + "['" + '"' + "])([^>]*>)"
        //Captures a <font color='colorString'> html tag.
        //Allows for additional attributes within the font
    Matcher matcher = pattern.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
            sb, + colorHex +;
    text = sb.toString();
    return text;

private static String getColorHex(int colorId, Context context){
    int colorContent = context.getResources().getColor(colorId);
    return String.format("#%06X", (0xFFFFFF & colorContent));