android gettext方法,android – getString()和getText()有什么区别?

我尝试使用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&gt ;,< i>,< u>.这种方法支持. source code似乎表明它支持的不仅仅是:< b&gt ;,< 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值