Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

In the case of the question - the colour passed into the ForegroundColorSpan was not yet resolved.

However on a side note, adding a ForegroundColorSpan to a TextView that has the attribute allCaps="true" will not work.

Remove the allCaps attribute, programatically change the capitalisation of the string BEFORE passing it to the constructor the SpannableStringBuilder.

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

When you pass R.color.XXX you are not passing the color int, rather you are passing the id of this resource in the generated R class - which is also an int, but one randomly generated by android. It's not your color, but it parses as one, and that's why your text gets a weird color.

To extract the literal color int from the id int you need to use something like ContextCompat.getColor(context, R.color.XXX)

This is confusing since in some cases we can set resources directly with R id's, such as with TextView.setText(int resId).

How can we tell? -simply check the annotation on the argument in the given function.

@ColorInt is expecting a literal color (like 0x0000ff -blue), such as in ForegroundColorSpan(@ColorInt int color).

@ColorRes is expecting an id int(R.color.blue), such as ContextCompat.getColor(@NonNull Context context, @ColorRes int id)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top