如何在Android中创建上下文? ContextThemeWrapper的目的是什么? [英] How is a context in Android created? What is the purpose of ContextThemeWrapper?

查看:218
本文介绍了如何在Android中创建上下文? 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:

  1. 是什么创建了Context,并使用了哪些具体类?基本的Context类本身是一个抽象类,它几乎需要实现其所有方法.实例化ContextWrapper时,需要传入一个Context实例作为其基础上下文,因此必须至少有一个具体的Context类.
  2. 我知道ContextWrapper及其子类利用包装器/装饰器模式根据需要向基本Context类添加功能. ContextThemeWrapper的目的是什么??它覆盖了一些方法,但是如果包装了基本的Context,为什么不只将调用委派给基本的Context呢?例如,Activity类扩展了ContextThemeWrapper,它为getTheme()setTheme()提供了一种特定的实现.为什么?
  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?

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆