当我从资源中读取字符串时为什么不能显示字体颜色?

时间:2015-07-04 04:21:20

标签: android

我希望用两个不同颜色的文本设置单个TextView,我已经阅读了文档

Single TextView with multiple colored text

代码A效果很好!

代码B从资源文件中获取字符串,但是字体的颜色无法显示,为什么?

代码A

 TextView my=(TextView) findViewById(R.id.tVTitleOld);
 String text = "<font color='#cc0029'>Hello</font> the <font color='#ffcc00'>world</font>";
 my.setText(Html.fromHtml(text));

代码B

 TextView my=(TextView) findViewById(R.id.tVTitleOld);
 String text = getResources().getString(R.string.TitleOld);
  my.setText(Html.fromHtml(text));


<string name="TitleOld"><font color='#cc0029'>Hello</font> the new <font color='#ffcc00'>world</font></string>

1 个答案:

答案 0 :(得分:2)

Strings.xml中的HTML代码应使用类似

的内容存储在CDATA中
<![CDATA[html source code]]>

因此,简而言之,您的代码将是

<string name="TitleOld"><![CDATA[<font color=\'#cc0029\'>Hello</font> the new <font color=\'#ffcc00\'>world</font>]]></string>

这是因为<作为&lt;存储在xml文件中,>存储为&gt;,依此类推。 CDATA保护实际文本,无论您需要显示什么内容。