Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to add ForegroundColorSpan

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.

like image 744
user1537779 Avatar asked Sep 10 '13 13:09

user1537779


2 Answers

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); 
like image 148
Raghunandan Avatar answered Sep 20 '22 11:09

Raghunandan


Some time you will use more than one span, they may influence each other. you should set ForegroundColorSpan at last.

like image 25
chen Avatar answered Sep 21 '22 11:09

chen