Christian Christian - 6 months ago 16
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
colors.xml
file?

I want to call
createColoredText(text)
and then have my TextView with the correct color.

Answer

I solved my problem myself with regex:

public static Spanned formatTextForTextView(String text, Context context){
    text = replaceColorForHex(text, "blue", R.color.blue, context);
    text = replaceColorForHex(text, "green", R.color.green, context);
    text = replaceColorForHex(text, "red", R.color.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
        //tag
    );
    Matcher matcher = pattern.matcher(text);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        matcher.appendReplacement(
            sb, matcher.group(1) + colorHex + matcher.group(3));
    }
    matcher.appendTail(sb);
    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));
}