Vandit Goel
Vandit Goel

Reputation: 793

Is accessing application resources via the Resource class same as accessing via the context?

Wile writing code I found out the that I can the access the string resources via calling the getString() function on both context

val string = context.getString(...)

and context.resources

val string = context.resources.getString(...)

Which is the right way to do it? Why the two ways?

Upvotes: 1

Views: 19

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006584

Which is the right way to do it?

Either is fine. The implementation of getString() is:

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

(from the source code)

So, they both do the same thing.

Why the two ways?

getString() is used a lot. Presumably, they added a helper method to Context to simplify access to string resources. However, while they do that for a couple of resource types, many others are only available via the full Resources object.

Upvotes: 2

Related Questions