无法添加ForegroundColorSpan

use*_*779 6 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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

RES /价值/ color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_blue">#FF39ACEE</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

颜色已改变,但改变了别的东西,而不是我想要的蓝色.

谢谢.

Rag*_*dan 15

试试这个

    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);
Run Code Online (Sandbox Code Playgroud)

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_blue">#FF39ACEE</color>
</resources>
Run Code Online (Sandbox Code Playgroud)

快照

在此输入图像描述

以下不起作用

ForegroundColorSpan fcs = new ForegroundColorSpan(R.color.text_blue);
sb.setSpan(fcs, 0, sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
Run Code Online (Sandbox Code Playgroud)

  • **工作:**这个`int color = getResources().getColor(R.color.text_blue); ForegroundColorSpan fcs = new ForegroundColorSpan(color);`做到了.非常感谢. (2认同)

Cha*_*lie 8

在问题的情况下 - 传递给它的颜色ForegroundColorSpan尚未解决.

然而在一个侧面说明,添加ForegroundColorSpanTextView具有属性allCaps="true"将无法正常工作.

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