gpt4 book ai didi

android - 何时使用 getString()

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:45 25 4
gpt4 key购买 nike

我想知道 getString()。我可以看到执行 getString(R.string.some_text) 是有效的。 getResources().getString(R.string.connection_error) 也有效。所以我的问题是为什么我们应该使用 getString 或者什么时候使用?谢谢!

最佳答案

这个问题很容易被误解。

如果您处于有效的上下文中(如 Activity),没有区别,因为上下文具有对资源的引用,因此它可以解析 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 对象做的不仅仅是“获取字符串”,你可以看看here .

现在与getString()的Activity版本进行比较:

Return a localized string from the application's package's default string table.

因此总而言之,除了 Resources 对象将去除任何样式文本信息这一事实。 并且 Resources 对象可以做很多,最终结果是一样的。 Activity 版本是一个方便的快捷方式:)

关于android - 何时使用 getString(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20538948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com