[英]Set TextView text from html-formatted string resource in XML
I have some fixed strings inside my strings.xml
, something like:我的
strings.xml
中有一些固定字符串,例如:
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
and in my layout I've got a TextView
which I'd like to fill with the html-formatted string.在我的布局中,我有一个
TextView
,我想用 html 格式的字符串填充它。
<TextView android:id="@+id/formattedtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/htmlstring"/>
if I do this, the content of formattedtext
is just the content of somestring
stripped of any html tags and thus unformatted.如果我这样做,
formattedtext
文本的内容只是剥离任何 html 标签的somestring
的内容,因此未格式化。
I know that it is possible to set the formatted text programmatically with我知道可以通过编程方式设置格式化文本
.setText(Html.fromHtml(somestring));
because I use this in other parts of my program where it is working as expected.因为我在我的程序的其他部分使用它,它按预期工作。
To call this function I need an Activity
, but at the moment my layout is just a simple more or less static view in plain XML and I'd prefer to leave it that way, to save me from the overhead of creating an Activity
just to set some text.要调用这个 function 我需要一个
Activity
,但目前我的布局只是一个简单的或多或少的 static 视图在普通 XML 中,我宁愿保持这种状态,以避免我创建Activity
的开销只是为了设置一些文本。
Am I overlooking something obvious?我是否忽略了一些明显的东西? Is it not possible at all?
难道根本不可能吗? Any help or workarounds welcome!
欢迎任何帮助或解决方法!
Edit: Just tried some things and it seems that HTML formatting in xml has some restraints:编辑:刚刚尝试了一些事情,似乎 xml 中的 HTML 格式有一些限制:
Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). 万一有人发现这个,有一个更好的替代品没有记录(我搜索了几个小时后绊倒了它,最后在Android SDK本身的bug列表中找到它)。 You CAN include raw HTML in strings.xml, as long as you wrap it in
您可以在strings.xml中原始的HTML,只要你把它包装
<![CDATA[ ...raw html... ]]>
Example: 例:
<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>
Then, in your code: 然后,在您的代码中:
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
IMHO, this is several orders of magnitude nicer to work with :-) 恕我直言,这是几个数量级更好的工作:-)
As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old: 由于这里的最佳答案是暗示出错 (或者至少过于复杂),我觉得应该更新,尽管问题已经很久了:
When using String resources in Android, you just have to call getString(...)
from Java code or use android:text="@string/..."
in your layout XML. 在Android中使用String资源时,您只需从Java代码调用
getString(...)
或在布局XML中使用android:text="@string/..."
。
Even if you want to use HTML markup in your Strings, you don't have to change a lot: 即使您想在字符串中使用HTML标记,也不必进行大量更改:
The only characters that you need to escape in your String resources are: 您需要在String资源中转义的唯一字符是:
"
becomes \\"
"
变成\\"
'
becomes \\'
'
变成\\'
&
becomes &
&
变成&
or &
&
That means you can add your HTML markup without escaping the tags: 这意味着您可以添加HTML标记而无需转义标记:
<string name="my_string"><b>Hello World!</b> This is an example.</string>
However, to be sure, you should only use <b>
, <i>
and <u>
as they are listed in the documentation. 但是,可以肯定的是,您应该只使用文档中列出的
<b>
, <i>
和<u>
。
If you want to use your HTML strings from XML , just keep on using android:text="@string/..."
, it will work fine. 如果你想使用XML中的HTML字符串,继续使用
android:text="@string/..."
,它将正常工作。
The only difference is that, if you want to use your HTML strings from Java code , you have to use getText(...)
instead of getString(...)
now, as the former keeps the style and the latter will just strip it off. 唯一的区别是,如果你想使用Java代码中的 HTML字符串,你现在必须使用
getText(...)
而不是getString(...)
,因为前者保留了样式而后者只是剥离它关了。
It's as easy as that. 就这么简单。 No CDATA, no
Html.fromHtml(...)
. 没有CDATA,没有
Html.fromHtml(...)
。
You will only need Html.fromHtml(...)
if you did encode your special characters in HTML markup. 您只需要
Html.fromHtml(...)
如果你没有编码的HTML标记的特殊字符。 Use it with getString(...)
then. 然后将它与
getString(...)
一起使用。 This can be necessary if you want to pass the String to String.format(...)
. 如果要将String传递给
String.format(...)
则可能需String.format(...)
。
This is all described in the docs as well. 这些都在文档中描述。
Edit: 编辑:
There is no difference between getText(...)
with unescaped HTML (as I've proposed) or CDATA
sections and Html.fromHtml(...)
. getText(...)
与未转义的HTML(正如我所提议的)或CDATA
部分和Html.fromHtml(...)
之间没有区别。
See the following graphic for a comparison: 请参阅以下图表以进行比较:
Escape your HTML tags ... 转义HTML标记...
<resources>
<string name="somestring">
<B>Title</B><BR/>
Content
</string>
</resources>
Android does not have a specification to indicate the type of resource string (eg text/plain or text/html). Android没有指定资源字符串类型的规范(例如text / plain或text / html)。 There is a workaround, however, that will allow the developer to specify this within the XML file.
但是,有一种解决方法可以让开发人员在XML文件中指定它。
Once you define these, you can express yourself with HTML in xml files without ever having to call setText(Html.fromHtml(...)) again. 一旦定义了这些,就可以用xml文件中的HTML表达自己,而无需再次调用setText(Html.fromHtml(...))。 I'm rather surprised that this approach is not part of the API.
我很惊讶这种方法不是API的一部分。
This solution works to the degree that the Android studio simulator will display the text as rendered HTML. 此解决方案适用于Android工作室模拟器将文本显示为呈现HTML的程度。
<resources>
<string name="app_name">TextViewEx</string>
<string name="string_with_html"><![CDATA[
<em>Hello</em> <strong>World</strong>!
]]></string>
</resources>
Declare the custom attribute namespace, and add the android_ex:isHtml attribute. 声明自定义属性命名空间,并添加android_ex:isHtml属性。 Also use the subclass of TextView.
还可以使用TextView的子类。
<RelativeLayout
...
xmlns:android_ex="http://schemas.android.com/apk/res-auto"
...>
<tv.twelvetone.samples.textviewex.TextViewEx
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/string_with_html"
android_ex:isHtml="true"
/>
</RelativeLayout>
<resources>
<declare-styleable name="TextViewEx">
<attr name="isHtml" format="boolean"/>
<attr name="android:text" />
</declare-styleable>
</resources>
package tv.twelvetone.samples.textviewex;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.text.Html;
import android.util.AttributeSet;
import android.widget.TextView;
public TextViewEx(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TextViewEx, 0, 0);
try {
boolean isHtml = a.getBoolean(R.styleable.TextViewEx_isHtml, false);
if (isHtml) {
String text = a.getString(R.styleable.TextViewEx_android_text);
if (text != null) {
setText(Html.fromHtml(text));
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
a.recycle();
}
}
}
Latest update: 最近更新:
Html.fromHtml(string);
//deprecated after Android N versions.. //在Android N版本之后弃用..
Following code give support to android N and above versions... 以下代码支持android N及以上版本...
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.setText(Html.fromHtml(yourHtmlString,Html.FROM_HTML_MODE_LEGACY));
}
else
{
textView.setText(Html.fromHtml(yourHtmlString));
}
String termsOfCondition="<font color=#cc0029>Terms of Use </font>";
String commma="<font color=#000000>, </font>";
String privacyPolicy="<font color=#cc0029>Privacy Policy </font>";
Spanned text=Html.fromHtml("I am of legal age and I have read, understood, agreed and accepted the "+termsOfCondition+commma+privacyPolicy);
secondCheckBox.setText(text);
I have another case when I have no chance to put CDATA into the xml as I receive the string HTML from a server. 我有另一种情况,当我从服务器收到字符串HTML时,我没有机会将CDATA放入xml。
Here is what I get from a server: 这是我从服务器得到的:
<p>The quick brown <br />
fox jumps <br />
over the lazy dog<br />
</p>
It seems to be more complicated but the solution is much simpler. 它似乎更复杂,但解决方案更简单。
private TextView textView;
protected void onCreate(Bundle savedInstanceState) {
.....
textView = (TextView) findViewById(R.id.text); //need to define in your layout
String htmlFromServer = getHTMLContentFromAServer();
textView.setText(Html.fromHtml(htmlFromServer).toString());
}
Hope it helps! 希望能帮助到你!
Linh 灵
Please follow this code请遵循此代码
Kotlin
var stringvalue = "Your Sting"
yourTextVew.text = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(stringvalue, Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(stringvalue)
}
Java
String stringvalue = "Your String";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
yourTextVew.setText(Html.fromHtml(stringvalue, Html.FROM_HTML_MODE_COMPACT))
} else {
yourTextVew.setText( Html.fromHtml(stringvalue))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.