Android:格式化文本部分不起作用

Yur*_*yak 2 android textview android-textattributes

在我的strings.xml文件中,我定义了以下内容:

<string name="mystring"><b>Bold text</b>Non-bold text</string>
Run Code Online (Sandbox Code Playgroud)

它应该工作,正如它在这里指定的那样.但实际上只显示粗体文本,文本的另一部分消失了.

K_A*_*nas 5

取自这个 SO线程

用这个

textView.setText(Html.fromHtml(someText));
Run Code Online (Sandbox Code Playgroud)

或者通过这种方式从xml

您可以在strings.xml中包含原始HTML,只要将其包装好即可

<![CDATA[ ...raw html... ]]>
Run Code Online (Sandbox Code Playgroud)

例:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Run Code Online (Sandbox Code Playgroud)

然后,在您的代码中:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
Run Code Online (Sandbox Code Playgroud)

你也可以在CDATA块里面反斜杠 - 转义撇号/单引号,这样你就可以有类似的东西<b>can\'t</b>而不是无限的丑陋<b>can&apos;t</b>