HTML标记在strings.xml中不起作用

Tro*_*omB 5 html java xml android

我试图在我的strings.xml中使用HTML标记<b>和</ b>根据此答案制作粗体文本:

<string name="name"><b>bold text here</b></string>
Run Code Online (Sandbox Code Playgroud)

然后尝试将文本设置如下:

TextView textview = new TextView(getActivity());
textview.setText(getString(R.string.name));
Run Code Online (Sandbox Code Playgroud)

但是这根本不起作用,标签被忽略,文本会定期显示.我已经能够使用以下方法使文本变为粗体:

<string name="name">&lt;b>bold text here&lt;/b></string>
Run Code Online (Sandbox Code Playgroud)

并使用Java中的此代码:

TextView textview = new TextView(getActivity());
textview.setText(Html.fromHtml(getString(R.string.name)));
Run Code Online (Sandbox Code Playgroud)

为什么简单的HTML标签不起作用,这另一种方法可以正常工作?

Ahm*_*mad 15

getText(int)而不是getString(int).

为什么简单的HTML标签不起作用,这另一种方法可以正常工作?

因为该getString(int)方法将返回一个字符串,即被删除样式化的文本信息,就像文档说的那样.

根据Android开发人员指南,getText(int)方法不会:

getText(int) 将保留应用于字符串的任何富文本样式.

有效的<string name="name">&lt;b>bold text here&lt;/b></string>解决方案,getString()因为您编码了小于号.

  • 当您需要将变量传递给 strings.xml 时,这不起作用 (2认同)