问题
I'm helping put together this page: What is a context?
To help illustrate how components are related to a Context
, I created this diagram from looking through the framework source code:
After digging around a bit, I had the following questions:
- What creates a
Context
and what concrete classes are used? The baseContext
class itself is an abstract class, which requires almost all of its methods to be implemented. And aContextWrapper
, when instantiated, requires aContext
instance to be passed in as it's base context, so there must be at least one concreteContext
class. - I understand that the
ContextWrapper
and its subclasses utilize the wrapper/decorator pattern to add functionality to the baseContext
class as needed. What is the purpose of theContextThemeWrapper
? It overrides a few methods, but if it's wrapping a baseContext
, why not just delegate the calls to the baseContext
? For example, theActivity
class extendsContextThemeWrapper
, which provides a specific implementation forgetTheme()
andsetTheme()
. Why?
The Android developer java docs are a bit vague. E.g., ContextWrapper
回答1:
Answering #2:
ContextThemeWrapper adds theming support to a Context, otherwise you can't apply any theme to the Views you create. That's why Activity layouts support themes while widget layouts don't, for example. You can also create a ContextThemeWrapper yourself to override the current theme with another one.
回答2:
Well, I am very late to the party, but The answer to #1 is I believe the ContextImpl class. It is created by the system and then whenever and any class (eg - Activity/Application) calls the attach
method which takes in a Context
as an argument and internally calls the attachBaseContext
of the ContextWrapper
class to setup the base context, this ContextImpl
is passed as the Context
argument.
Thus the ContextImpl
class provides a solid implementation of the Context
class.
来源:https://stackoverflow.com/questions/31460707/how-is-a-context-in-android-created-what-is-the-purpose-of-contextthemewrapper