gpt4 book ai didi

android - 使用 xml 文件中定义的颜色为 android TextView 中的部分文本着色

转载 作者:行者123 更新时间:2023-11-30 01:19:01 25 4
gpt4 key购买 nike

我有从外部源加载的文本。我可以控制外部源如何定义字符串。

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

有没有办法指定 Android 不应该使用标准 CSS 颜色红色,而是使用我在 colors.xml 文件中定义的红色?

我想调用 createColoredText(text) 然后让我的 TextView 具有正确的颜色。

最佳答案

我自己用正则表达式解决了我的问题:

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));
}

关于android - 使用 xml 文件中定义的颜色为 android TextView 中的部分文本着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37390035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com