How is a context in Android created? What is the purpose of ContextThemeWrapper?

只愿长相守 提交于 2020-08-21 06:01:06

问题


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:

Context Subclasses

After digging around a bit, I had the following questions:

  1. What creates a Context and what concrete classes are used? The base Context class itself is an abstract class, which requires almost all of its methods to be implemented. And a ContextWrapper, when instantiated, requires a Context instance to be passed in as it's base context, so there must be at least one concrete Context class.
  2. I understand that the ContextWrapper and its subclasses utilize the wrapper/decorator pattern to add functionality to the base Context class as needed. What is the purpose of the ContextThemeWrapper? It overrides a few methods, but if it's wrapping a base Context, why not just delegate the calls to the base Context? For example, the Activity class extends ContextThemeWrapper, which provides a specific implementation for getTheme() and setTheme(). 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!