Resources类中getString (int ResID)与getText (int ResID)的区别

Resources类中getString (int ResID)与getText (int ResID)的区别

getString (int ResID)和getText (int ResID)都是Resources类中方法,都是获取资源文件中的字符串资料。

  • getString (int ResID):是获得资源文件的字符串资源(XML文件中String子元素定义的String资源),但是没有任何的文本显示样式的,其仅仅是获取字符串的值而已。
  • getText (int ResID):也是获取XML文件中String子元素定义的String资源,与getString()方法不同的是,getText()返回的字符串包含文本的格式信息。

下面先看看二者在API的定义:

(1)public CharSequence getText (int ResID)

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.

返回与特定资源ID相关联的字符串值。如果是无格式的字符串,则返回的是字符串对象,如是格式的字符串,则将返回CharSequence 其他类型。

  • 参数说明:

ResIDThe desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

  • 返回值:

CharSequence The string data associated with the resource, plus possibly styled text information.(与资源想关联的字符串数据和可能有的文本信息样式)

 (2) public String getString (int ResID)

Return the string value associated with a particular resource ID. It will be stripped of(剥夺) any styled text information.

返回与特定资源ID相关联的字符串值。返回的字符串值被去除了全部文本信息的样式

  • 参数说明:

ResID The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.

  • 返回值:

String :The string data associated with the resource, stripped of styled text information.

(3) getString (int ResID)与getText (int ResID)的区别

二者都是在Resource类中的定义的方法,都是获取资源文件中的字符串资料。

  • getString (int ResID):是获得资源文件的字符串资源(XML文件中String子元素定义的String资源),但是没有任何的文本显示样式的,其仅仅是获取字符串的值而已。
  • getText (int ResID):也是获取XML文件中String子元素定义的String资源,与getString()方法不同的是,getText()返回的字符串包含文本的格式信息。

例如:

Strings.xml文件内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="demo">  <b>demo</b> </string>
</resources>

在主程序中的主要语句:

CharSequence chs = getText(R.string.demo);  //包含文本的样式信息
String str = getString(R.string.demo);  //没有任何的文本样式信息
Text1.setText(chs);  
Text2.setText(str);

运行结果如下:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI吃大瓜

尊重原创,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值