要想回答这一问题,我们需要先从 Activity 的基类入手
来看 Context 类,该类是一个抽象类,为访问应用程序的环境信息提供了全局的接口,通过它可以访问到应用程序的资源,类型,以及运行中的 Activitys ,正在广播和接收中的 Intents 等。
/** Return a Resources instance for your application's package. */
public abstract Resources getResources();
/**
* Set the base theme for this context. Note that this should be called
* before any views are instantiated in the Context (for example before
* calling {@link android.app.Activity#setContentView} or
* {@link android.view.LayoutInflater#inflate}).
*
* @param resid The style resource describing the theme.
*/
public abstract void setTheme(int resid);
/**
* Return the Theme object associated with this Context.
*/
public abstract Resources.Theme getTheme();
既然 Context 类是一个抽象类,没有提供具体的实现,我们就循迹来看它的子类 ContextWrapper 类,该类是一个具本类,实现了 Context 的接口,但实现方式很简单,只是简单的委托给其他的 Context 对象。例如:
@Override
public Resources getResources()
{
return mBase.getResources();
}
@Override
public void setTheme(int resid) {
mBase.setTheme(resid);
}
@Override
public Resources.Theme getTheme() {
return mBase.getTheme();
}
继续来看 ContextWrapper 的子类 ContextThemeWrapper ,该类是针对 Context 主题部分的包装类,其主要功能是主题变换,在 GetTheme() 中通过 initializeTheme() 的调用将主题启用。
protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
theme.applyStyle(resid, true);
}
private void initializeTheme() {
final boolean first = mTheme == null;
if (first) {
mTheme = getResources().newTheme();
Resources.Theme theme = mBase.getTheme();
if (theme != null) {
mTheme.setTo(theme);
}
}
onApplyThemeResource(mTheme, mThemeResource, first);
}
至此, Activity 派生于 ContextThemeWrapper ,就具备了变换主题的能力了。