roi*_*erg 4 string android getstring
我想知道getString().我可以看到这样做getString(R.string.some_text)有效.也getResources().getString(R.string.connection_error)有效.所以我的问题是为什么我们应该使用getString或什么时候?谢谢!
这个问题很容易被误解.
如果您处于有效的上下文(如Activity),则没有区别,因为上下文具有对资源的引用,因此它可以getString(int);直接解析,返回String.
添加更多信息,让您高枕无忧.
如果您可以直接使用getString,请继续执行.现在有时您可能需要使用getResources(),因为它包含许多辅助方法.
这是Android的源代码getResources.getString():
/**
* Return the string value associated with a particular resource ID. It
* will be stripped of any styled text information.
* {@more}
*
* @param id 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.
*
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @return String The string data associated with the resource,
* stripped of styled text information.
*/
public String getString(int id) throws NotFoundException {
CharSequence res = getText(id);
if (res != null) {
return res.toString();
}
throw new NotFoundException("String resource ID #0x"
+ Integer.toHexString(id));
}
Run Code Online (Sandbox Code Playgroud)
整洁吧?:)
事实是,Resources对象不仅仅是"获取字符串",你可以看看这里.
现在与getString()的Activity版本进行比较:
从应用程序包的默认字符串表中返回本地化字符串.
总而言之,除了Resources对象be stripped of any styled text information.以及Resources对象可以做更多事实之外,最终结果是相同的.Activity版本是一个方便的快捷方式:)
| 归档时间: |
|
| 查看次数: |
3701 次 |
| 最近记录: |