我尝试使用getString()从我的string.xml中获取一个字符串
然而.我刚刚发现getText()方法可以从我的资源中获取HTML标记!
说:
Hello Guys
它让我感到惊讶,因为我不得不使用Html.fromHtml()来获取HTML标签 – 这是不推荐使用的.
这两种方法有什么区别?
有优势还是劣势?
解决方法:
来自doc,
对于Resources.getString():
Return the string value associated with a particular resource ID. It
will be stripped of any styled text information.
对于Resources.getText():
Return the string value associated with a particular resource ID. The
returned object will be a String if this is a plain string; it will be
some other type of CharSequence if it is styled.
[注意,Context.getText()和Context.getString()在内部调用Resources中的方法.
doc说getText()保留了样式,而getString()没有.但是您可以使用其中任何一个从strings.xml获取带有HTML标记的字符串资源,但方式不同.
使用Resources.getText():
strings.xml中:
Hello, World!
你可以调用getText()(注意它返回一个CharSequence而不是String,因此它具有样式属性)并将文本设置为TextView.不需要Html.fromHtml().
mTextView.setText(getText(R.string.styled_text));
但是doc仅表示有限的HTML标签,例如< b> ;,< i>,< u>.这种方法支持. source code似乎表明它支持的不仅仅是:< b> ;,< i>,< u>,< big>,< small>,< sup>,< sub>,< strike> ,< li>,< marquee>,< a>,< font>和
使用Resources.getString():
strings.xml中:
World!]>
您必须在CDATA块中包围您的字符串,并且调用getString将返回带有HTML标记的字符串.在这里你必须使用Html.fromHtml().
mTextView.setText(Html.fromHtml( getString(R.string.styled_text)));
不推荐使用Html.fromHtml()以支持带有flags参数的新方法.所以像这样使用它:
HtmlCompat.fromHtml(getString(R.string.styled_text))
util方法HtmlCompat.fromHtml的实现:
public class HtmlCompat {
public static CharSequence fromHtml(String source) {
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
//noinspection deprecation
return Html.fromHtml(source);
} else {
return Html.fromHtml(source, Html.FROM_HTML_MODE_COMPACT);
}
}
}
标签:html,android
来源: https://codeday.me/bug/20191007/1868555.html