无法添加ForegroundColorSpan

时间:2013-09-10 13:35:25

标签: android spannable

SpannableStringBuilder sb = new SpannableStringBuilder("Hello World");
ForegroundColorSpan fcs = new ForegroundColorSpan(R.color.text_blue);
sb.setSpan(fcs, 5, 11,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

enter image description here

RES /值/ color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_blue">#FF39ACEE</color>
</resources>

颜色发生了变化,但变成了别的东西,而不是我想要的蓝色。

谢谢。

4 个答案:

答案 0 :(得分:14)

试试这个

    SpannableStringBuilder sb = new SpannableStringBuilder("Hello World");
    int color = getResources().getColor(R.color.text_blue);
    ForegroundColorSpan fcs  =new ForegroundColorSpan(color);
    sb.setSpan(fcs, 0, sb.length(),0);
    TextView tv= (TextView) findViewById(R.id.textView1);
    tv.setText(sb);

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_blue">#FF39ACEE</color>
</resources>

对齐

enter image description here

以下不起作用

ForegroundColorSpan fcs = new ForegroundColorSpan(R.color.text_blue);
sb.setSpan(fcs, 0, sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

答案 1 :(得分:7)

在问题的情况下 - 传递到ForegroundColorSpan的颜色尚未解决。

但是在旁注中,将ForegroundColorSpan添加到具有属性TextView的{​​{1}}将无效。

删除allCaps="true"属性,以编程方式更改字符串的大小写,然后将其传递给构造函数allCaps

答案 2 :(得分:2)

有时您将使用多个跨度,它们可能会相互影响。您应该最后设置ForegroundColorSpan。

答案 3 :(得分:0)

当您传递R.color.XXX时,您并没有传递 color int ,而是在生成的id类中传递了该资源的R-也是一个int,但是由Android随机生成的一个 。不是您的颜色,而是将其解析为一种,这就是为什么您的文本使用奇怪的颜色的原因。

要从 id int 中提取文字颜色int ,您需要使用ContextCompat.getColor(context, R.color.XXX)

之类的东西

这令人困惑,因为在某些情况下,我们可以直接使用R id(例如TextView.setText(int resId))来设置资源。

我们怎么知道? -只需检查给定函数中参数的注释。

@ColorInt期望使用文字颜色(例如0x0000ff -blue),例如ForegroundColorSpan(@ColorInt int color)中的颜色。

@ColorRes期望一个id int(R.color.blue),例如ContextCompat.getColor(@NonNull Context context, @ColorRes int id)