问题
I have just started learning android programming and I came up with a doubt about the method getResources().
I noticed that when I create a Resources object all I have to do is:Resources res = getResources();
The first doubt is the following why do I have to do in that way and I mustn't use the java keyword new? Shouldn't I do something like this:
Resources res = new Resources();
The second doubt is the following: at the top of my file I have imported the Resources class.
import android.content.res.Resources;
Now I read the android api and it says that getResources() is a public abstract method, if it is abstract which class implements it? how can I simply call it typing getResources() if it is not declared as static?
回答1:
Your activity extends class android.app.Activity which in turn extends class android.content.Context (three levels up the class hierarchy). Class Context
declares the abstract method getResources() which means that your activity subclass inherits that method and you can call it from within your onCreate()
method (for example).
The method getResources()
is declared as abstract in class Context
but one of the intermediate classes in the class hierarchy (android.view.ContextThemeWrapper) provides an implementation for the method.
Also that means that creating the Resources
object is not your responsibility; it is done by the framework instead.
回答2:
getResources is actually a method you can access from your Context. So you can really think of this as:
context.getResources()
Your Activity class is your context in this case, which is why you can just call it with the syntax:
getResources()
http://developer.android.com/reference/android/content/Context.html#getResources%28%29
From those docs:
Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.
来源:https://stackoverflow.com/questions/16922890/implementation-of-getresources-android