android–getString()和getText()有什么区别?

android–getString()和getText()有什么区别?,第1张

概述我尝试使用getString()从我的string.xml中获取一个字符串然而.我刚刚发现getText()方法可以从我的资源中获取HTML标记!说:<stringname="mySTring"><b><i>HelloGuys</i></b></string>它让我感到惊讶,因为我不得不使用Html.fromHtml()来获取HTML标签–这是不推荐使用的.这两

我尝试使用getString()从我的string.xml中获取一个字符串
然而.我刚刚发现getText()方法可以从我的资源中获取HTML标记!

说:

<string name="mySTring"><b><i>Hello Guys</i></b></string>

它让我感到惊讶,因为我不得不使用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中:

<string name="styled_text">Hello, <b>World</b>!</string>

你可以调用getText()(注意它返回一个CharSequence而不是String,因此它具有样式属性)并将文本设置为TextVIEw.不需要HTML.fromHTML().

mTextVIEw.setText(getText(R.string.styled_text));

但是doc仅表示有限的HTML标签,例如< b&gt ;,< i>,< u>.这种方法支持. source code似乎表明它支持的不仅仅是:< b&gt ;,< i>,< u>,< big>,< small>,< sup>,< sub>,< strike> ,< li>,< marquee>,< a>,< Font>和<注释>

使用Resources.getString():

strings.xml中:

<string name="styled_text"><![cdaTA[Hello, <b>World</b>!]></string>

您必须在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);        }    }}
总结

以上是内存溢出为你收集整理的android – getString()和getText()有什么区别?全部内容,希望文章能够帮你解决android – getString()和getText()有什么区别?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1096781.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存