When and why should one use getResources()?
I'm just getting started with Android dev and playing around.
The documentation for getResources() says that it开发者_StackOverflow中文版 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
if(countryName.equals("us")){
imageview.setImageRsource(R.drawable.us);
}
OR
Resources res = getResources();
int imageId = res.getIdentifier(getIdentifier(countryName, "drawable"
,"com.myapp");
imageview.setImageRsource(imageId);
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
res.getAssets().open(YOUR FILE);
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.
It will be useful in non_activity classes.
You will pass the context to the class and from that you can access the resources.
A class that inherits Activity also inherits getResources(). If you have a class that is an Activity (or a derivative thereof) you have access to this method (via inheritance, a really, really basic concept in object oriented programming. If you have a class that isn't a derivative of such a class, you need to grant access to such a context for access to said resources.
If you need more information about inheritance, polymorphism, or etc. regarding object oriented programming, I suggest referring to various websites or school curricula touching upon such issues.
精彩评论