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);
        }
    }

}

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...