如何在Android中创建上下文? ContextThemeWrapper的目的是什么? [英] How is a context in Android created? What is the purpose of ContextThemeWrapper?
问题描述
我正在帮助整理以下页面:什么是上下文?
I'm helping put together this page: What is a context?
为帮助说明组件与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:
- 是什么创建了
Context
,并使用了哪些具体类?基本的Context
类本身是一个抽象类,它几乎需要实现其所有方法.实例化ContextWrapper
时,需要传入一个Context
实例作为其基础上下文,因此必须至少有一个具体的Context
类. - 我知道
ContextWrapper
及其子类利用包装器/装饰器模式根据需要向基本Context
类添加功能.ContextThemeWrapper
的目的是什么??它覆盖了一些方法,但是如果包装了基本的Context
,为什么不只将调用委派给基本的Context
呢?例如,Activity
类扩展了ContextThemeWrapper
,它为getTheme()
和setTheme()
提供了一种特定的实现.为什么?
- 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?
Android开发人员的Java文档有点含糊.例如 ContextWrapper
The Android developer java docs are a bit vague. E.g., ContextWrapper
推荐答案
答案2:
ContextThemeWrapper将主题支持添加到Context,否则您不能将任何主题应用于所创建的View.例如,这就是为什么活动布局支持主题而小部件布局不支持主题的原因.您还可以自己创建一个ContextThemeWrapper,以另一个替换当前主题.
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.
这篇关于如何在Android中创建上下文? ContextThemeWrapper的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!