Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/232.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 无法添加ForegroundColorSpan_Android_Spannable - Fatal编程技术网

Android 无法添加ForegroundColorSpan

Android 无法添加ForegroundColorSpan,android,spannable,Android,Spannable,res/Values/color.xml SpannableStringBuilder sb = new SpannableStringBuilder("Hello World"); ForegroundColorSpan fcs = new ForegroundColorSpan(R.color.text_blue); sb.setSpan(fcs, 5, 11,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); #FF39ACEE 颜色变了,但换成了别的颜色,而不

res/Values/color.xml

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

#FF39ACEE
颜色变了,但换成了别的颜色,而不是我想要的蓝色

谢谢。

试试这个

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

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

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

但是,另一方面,向具有属性
allCaps=“true”
TextView
添加
ForegroundColorSpan
将不起作用


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

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

当您传递
R.color.XXX
时,您并没有传递color int,而是在生成的
R
类中传递该资源的
id
,该类也是一个int,但由android随机生成。这不是你的颜色,但它作为一个解析,这就是为什么你的文本得到一个奇怪的颜色

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

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

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

@ColorInt
需要文字颜色(如
0x0000ff
-blue),如
ForegroundColorSpan(@ColorInt-color)


@ColorRes
需要一个id int(
R.color.blue
),比如
ContextCompat.getColor(@NonNull Context Context,@ColorRes int id)

它给了我正确的颜色在我的模拟器上试过它也给了我正确的颜色,无论是在模拟器上还是在设备上,你正在检查哪个模拟器/设备??如果可能的话,检查真实设备。我正在设备上尝试。奇怪的是,我更改了长度,并且文本不显示蓝色。更改为
sb.setSpan(fcs,0,sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
,此操作有效
new ForegroundColorSpan(Color.BLUE)在上测试emulator@Raghunandan哪个有效?有效:This
int color=getResources().getColor(R.color.text\u blue);ForegroundColorSpan fcs=新的ForegroundColorSpan(颜色)成功了。非常感谢。在实施多跨时,请注意这一点非常重要!
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="text_blue">#FF39ACEE</color>
</resources>
ForegroundColorSpan fcs = new ForegroundColorSpan(R.color.text_blue);
sb.setSpan(fcs, 0, sb.length(),Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);