我想知道getString()。我可以看到做getString(R.string.some_text)是有效的。同样,getResources().getString(R.string.connection_error)也能工作。所以我的问题是为什么我们要使用getString或者什么时候使用?谢谢!
发布于 2013-12-12 09:07:45
这个问题很容易被误解。
如果您在一个有效的上下文中(比如一个活动),没有什么区别,因为上下文有一个对资源的引用,所以它可以直接解析一个getString(int);,它返回一个字符串。
添加更多的信息,让你安心。
如果你可以直接使用getString,那就去做吧。现在,有时您可能需要使用getResources(),因为它包含了很多帮助方法。
这是getResources.getString()的Android源代码。
/**
* 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));
}整洁,哈?)
事实上,Resources对象所做的不仅仅是“获取字符串”,您可以查看一下这里。
现在将其与getString()的活动版本进行比较
从应用程序包的默认字符串表返回本地化字符串。
总之,除了Resources对象将be stripped of any styled text information.和Resources对象可以做的更多这一事实之外,最终的结果是相同的。活动版本是一个方便的快捷方式:)
发布于 2013-12-12 09:07:39
方法是一样的。从逻辑上讲,没有什么不同。你可以假设,它确实做到了:
public final String getString(int resId) {
return getResources().getString(resId);
}我所知道的唯一不同之处是,可能需要getResources()作为对象来获取其他应用程序资源。getString()将访问您自己的资源。
发布于 2013-12-12 09:02:44
如果将它用于TextView,其中有两个方法setText()。一个是(CharSequence字符串),另一个是(int resId)。这就是为什么两种变体都能工作的原因。
通常,我建议定义strings.xml文件中的所有字符串,并通过代码中的getResources().getString(int resId)获取它们。有了这种方法,您将能够轻松地本地化您的应用程序。您可以阅读有关应用程序资源这里的更多信息。
https://stackoverflow.com/questions/20538948
复制相似问题