【问题标题】:Why can't the font color be displayed when I read a string from resource?为什么我从资源中读取字符串时无法显示字体颜色?
【发布时间】:2015-07-04 04:21:19
【问题描述】:

我希望用两个不同颜色的文本设置单个 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>

【问题讨论】:

    标签: android


    【解决方案1】:

    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>
    

    这是因为&amp;lt;在xml文件中存储为&amp;lt;&amp;gt;&amp;gt;等等。 CDATA 维护您需要显示的实际文本。

    【讨论】:

    • 谢谢!但是您的代码不起作用,它会显示 ![CDATA[html source code]]
    • 使用 ![CDATA[Hello 新的世界]]
    • 是的,我确实使用了 ![CDATA[Hello 新的 世界]] ,但它不起作用
    • 对不起。我发帖前没有测试。这肯定会起作用(刚刚测试过)。 &lt;string name="TitleOld"&gt;&lt;![CDATA[&lt;font color=\'#cc0029\'&gt;Hello&lt;/font&gt; the new &lt;font color=\'#ffcc00\'&gt;world&lt;/font&gt;]]&gt;&lt;/string&gt;
    • 还有更多,我希望在 中设置新行,但是 \n 和 都不起作用。我能怎么做?谢谢! Hello \n 新的新 世界]]>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多