要想回答这一问题,我们需要先从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,就具备了变换主题的能力了。