【发布时间】:2012-03-09 14:12:55
【问题描述】:
有没有办法在android中设置字符串资源的颜色?我的意思是,我知道我可以使用一些 html 标签来更改字符串样式(或子字符串),但没有找到任何可以更改颜色的标签。我在 stackoverflow 看到了其他解决方案,例如在设置文本之前将字符串传递给 Html.fromHtml(string) 但我想在字符串资源编辑器中进行。有没有可能?
【问题讨论】:
标签: android string android-widget
有没有办法在android中设置字符串资源的颜色?我的意思是,我知道我可以使用一些 html 标签来更改字符串样式(或子字符串),但没有找到任何可以更改颜色的标签。我在 stackoverflow 看到了其他解决方案,例如在设置文本之前将字符串传递给 Html.fromHtml(string) 但我想在字符串资源编辑器中进行。有没有可能?
【问题讨论】:
标签: android string android-widget
看起来this 方法有效:
<string name="some_text">this is <font fgcolor="#ffff0000">red</font></string>
【讨论】:
7fffffff 的任何颜色,应用以下内容:<font color="#ff6890a5"> 将 ff6890a5 放入计算器(可选转换为十进制首先)并翻转符号,然后(可选地转换回十六进制)取最后 8 个十六进制数字并使用<font color="-#00976F5B">。
Resources.getText(id:) 方法,您可以在font 元素中使用color 属性而不是fgcolor。
据我所知,这是不可能的。我会使用 SpannableString 来改变颜色。
int colorBlue = getResources().getColor(R.color.blue);
String text = getString(R.string.text);
SpannableString spannable = new SpannableString(text);
// here we set the color
spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0);
Spannable 真的很棒。您可以在其中设置诸如 fontseize 之类的想法,然后将其附加到文本视图中。优点是您可以在一个视图中拥有不同的颜色。
编辑:好的,如果你只想设置颜色,我上面提到的解决方案就是要走的路。
【讨论】:
int colorBlue = getResources().getColor(R.color.blue); .... spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0); 可以用这样的单行替换spannable.setSpan(new ForegroundColorSpan(R.color.blue) ..
字符串本身没有颜色,但是你可以在它们出现的textView中改变文本的颜色。参见textview documentation,但是有2种方法可以做到。
XML
android:textColor
代码
setTextColor(int)
【讨论】:
我最近为这个问题做了一个灵活的解决方案。它使我能够通过使用方法链接轻松地将多种样式添加到子字符串中。它使用 SpannableString。当你想给某个子字符串一个颜色时,你可以使用 ForegroundColorSpan。
public StyledString putColor(String subString, @ColorRes int colorRes){
if(getStartEnd(subString)){
int color = ColorUtil.getColor(context, colorRes);
ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
fullStringBuilder.setSpan(foregroundColorSpan, startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return this;
}
完整代码见gist。
【讨论】: