I’m just getting started with Android dev and playing around.
The documentation for getResources() says that it will [r]eturn a Resources instance for your application's package.
In code examples I’ve seen this used to access the resources in res, but it seems like you can just access them directly.
For example to retrieve my_string from res/values/strings.xml:
<!-- strings.xml -->
...
<string name="my_string">This is my string</string>
...
You can use these two ways
The first way:
// MyActivity.java //
...
// No need to use getResources()
String msg = getString(R.string.my_string);
...
The second way:
// MyActivity.java //
...
// What is the point of getResources() here?
// It works but it requires "import android.content.res.Resources;" and is longer
Resources the_resources = this.getResources();
String msg = the_resources.getString(R.string.my_string);
...
So, when would you be required to use getResources() to access a resource? Seems like it is not necessary, or is it being call implicitly, or must it be called to access certain other types of resources or to access resources in other ways?
Resources have many helper methods that we may require.
R.id, R.drawable all return dynamic int assigned by android during build time. Suppose we have a requirement where we require to access a coutries flag image based on its name.
If we have image name as us.png and the value we have is ‘us’. The 2 ways to handle it are
OR
The second method will be the way to go especially when there are more than 50 countries or you will end up with a very long if-else or switch statement.
The resources object is also used when you need to access the contents in the Assets folder
Resource instance can also be passed to other class files to access the the resources. These are some of the scenarios that you can use it for.