How to change the colors of certain words in the string stored in strings.xml?

advertisements

I have found some solutions on how to change the color of specific characters and words of a string stored in strings.xml, however, it is not working for me. I have the following string

<string name="my_string">
       Humpty Dumpty sat on a <font fgcolor="#FF0000">wall</font> Humpty Dumpty had a great <font fgcolor="#FF0000">fall</font></string>

I was expecting the words wall and fall to be the color of #FF0000 (red), however, they do not display at all. After further research I learned that you have to declare the alpha channel, so then I updated my string to

<string name="my_string">
       Humpty Dumpty sat on a <font fgcolor="#FFFF0000">wall</font> Humpty Dumpty had a great <font fgcolor="#FFFF0000">fall</font></string>

My declared alpha channel is fully opaque, yet the results remain the same.

Lastly, I also tried using CDDATA, this is my attempt with that.

<string name="my_string"><![CDATA[
       Humpty Dumpty sat on a <font color=\'#FF0000\'>wall</font> Humpty Dumpty had a great <font color=\'#FF0000\'>fall</font>]]</string>

What else am I doing wrong? Thanks in advance!


You're suppose to use something like this.

textView.setText(Html.fromHtml(getString(R.string.some_text)));

and your strings.xml should contain the string as follows.

<string name="some_text"><![CDATA[<font color=\'#cc0029\'>Some</font> random <font color=\'#ffcc00\'>text</font>]]></string>

Check here for more details.