android string.xml读取html标签的问题

d-m*_*man 47 string android

在Android项目的strings.xml文件中,我有以下html文本

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="myHeadStr"><b><u>bold, underline </u></b></string>
...

</resources>
Run Code Online (Sandbox Code Playgroud)

当我把它读入getString(R.string.myHeadStr)时,它只给出文本"粗体,下划线"它忘记了html标签和....

如何从string.xml中读取带有html标记的完整字符串

mei*_*ilp 107

使用XML CDATA

<string name="demoStr"><Data><![CDATA[ <b>ABC</b> ]]> </Data></string>
Run Code Online (Sandbox Code Playgroud)

getString()将被获得 "<b>ABC</b>"

  • 不,它不是,这太复杂了:http://stackoverflow.com/a/18199543/89818 (2认同)

Sar*_*fan 36

替换<with<

<string name="myHeadStr">&lt;b>&lt;u>bold, underline &lt;/u>&lt;/b></string>
Run Code Online (Sandbox Code Playgroud)

然后,在检索时:

Html.fromHtml(getResources().getString(R.string.myHeadStr));
Run Code Online (Sandbox Code Playgroud)

这是在android文档中执行的规定方式.阅读以下链接中标题为"使用HTML标记设置样式"的段落:http: //developer.android.com/guide/topics/resources/string-resource.html

  • 当我使用它时,它会沿着标签打印数据,而不是html格式 (2认同)

Abt*_*ian 8

直接将字符串资源ID传递给setText()使用或Context.getText()不使用都Html.fromHtml()可以正常工作,但传递的结果Context.getString()却不能。

例如:

strings.xml

<resources>
    <string name="html">This is <b>bold</b> and this is <i>italic</i>.</string>
<resources>
Run Code Online (Sandbox Code Playgroud)

Activity.java文件中的代码:

textView.setText(R.string.html); // this will properly format the text
textView.setText(getText(R.string.html)); // this will properly format the text
textView.setText(getString(R.string.html)); // this will ignore the formatting tags
Run Code Online (Sandbox Code Playgroud)