Android 无法添加ForegroundColorSpan
res/Values/color.xmlAndroid 无法添加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 颜色变了,但换成了别的颜色,而不
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哪个有效?有效:Thisint 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);