Unable to add ForegroundColorSpan

user1537779 picture user1537779 · Sep 10, 2013 · Viewed 8.7k times · Source
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/Values/color.xml

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

The color has changed but to something else, rather than the blue color I wanted.

Thank You.

Answer

Raghunandan picture Raghunandan · Sep 10, 2013

Try this

    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>

Snap

enter image description here

The below did not work

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