微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我尝试使用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);
        }
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐