6

我想知道getString()。我可以看到这样做getString(R.string.some_text)是有效的。也getResources().getString(R.string.connection_error)有效。所以我的问题是我们为什么要使用 getString 或何时使用?谢谢!

4

5 回答 5

5

这个问题很容易被误解。

如果你在一个有效的上下文中(比如一个Activity),没有区别,因为上下文有一个对资源的引用,所以它可以getString(int);直接解析a,它返回一个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));
    }

整齐吧?:)

事实上,Resources 对象不仅仅是“获取字符串”,您可以查看这里

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

从应用程序包的默认字符串表中返回本地化字符串。

So in summary, other than the fact that the Resources object will be stripped of any styled text information. and that the Resources object can do a lot more, the end result is the same. The Activity version is a convenient shortcut :)

于 2013-12-12T09:07:45.363 回答
2

方法是一样的。从逻辑上讲,没有区别。你可以假设,它确实是:

public final String getString(int resId) {
 return getResources().getString(resId);
 }

我知道的唯一区别是getResources()可能需要获取其他应用程序资源作为对象。getString() 将访问您自己的资源。

于 2013-12-12T09:07:39.180 回答
1

如果将它用于 TextView,则其中有两种方法 setText()。一个需要(CharSequence 字符串),另一个需要(int resId)。这就是为什么您的两种变体都有效的原因。

一般来说,我建议在 strings.xml 文件中定义所有字符串,并通过代码中的 getResources().getString(int resId) 获取它们。采用这种方法,您将能够轻松本地化您的应用程序。您可以在此处阅读有关应用资源的更多信息

于 2013-12-12T09:02:44.263 回答
1

非常基本的区别。

R.string.some_text = return ID integer, identifying string resource in your space
getResources().getString(R.string.connection_error) = Will return you actualy string associated with ID `R.string.connection_error`

它们都可以在 Android 系统中使用,其中许多小部件可以直接获取资源的 id 或 value。实际上,返回的值没有区别,唯一的区别是 Term Context,您可以使用活动上下文,因此可以getString直接调用此上下文的资源路由,而从适配器中说上下文不可用的类,您将需要首先访问上下文,然后访问与上下文关联的资源,最后访问字符串,这样您就可以编写getContext().getResources().getString(R.string.connection_error)

我希望它能消除你的困惑。

于 2013-12-12T09:05:12.887 回答
0

One good reason is about formating & styling like :(http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling)

于 2013-12-12T09:07:52.373 回答