Android源码学习之一-Activity是如何实现主题变化的

本文解析了Android中如何通过继承ContextThemeWrapper实现主题设置的过程。从Context类的基本功能介绍开始,逐步深入到ContextWrapper及ContextThemeWrapper的具体实现细节,最终解释了Activity如何获得主题变换能力。

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

——欢迎转载,请注明出处,谢谢——

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值