天天看点

android换肤哪个简单,Android一键换肤功能实现

市面上对数的App都提供换肤功能,这里暂且不讲白天和夜间模式

下图是网易云音乐的换肤功能

android换肤哪个简单,Android一键换肤功能实现

经典

android换肤哪个简单,Android一键换肤功能实现

换肤其实就是替换资源(文字、颜色、图片等)

一、换肤模式:

1.内置换肤

在Apk包中存在多种资源(图片、颜色值)用于换肤时候切换。

自由度低,apk文件大  一般用于没有其他需求的日间/夜间模式app

2.动态换肤

通过运行时动态加载皮肤包

android换肤哪个简单,Android一键换肤功能实现

网易云下载的资源包

二、换肤流程

android换肤哪个简单,Android一键换肤功能实现

流程

2.1 采集

android换肤哪个简单,Android一键换肤功能实现

采集

2.2 如何采集

怎么才能拿到所有的view这才是关键!那么我们只能从setContentView()入手

那么问题来了setContentView()到底干了什么

查看源码发现setContentView()通过LayoutInflater将xml转换成View加载到window中

android换肤哪个简单,Android一键换肤功能实现

源码三连

inflate干了什么?

android换肤哪个简单,Android一键换肤功能实现

干货来了!!!!

LayoutInflate 的核心是createViewFromTag()

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,

boolean ignoreThemeAttr) {

...............

View view;

if (mFactory2 !=null) {//核心View的创建工厂 是一个接口

view =mFactory2.onCreateView(parent, name, context, attrs);

}else if (mFactory !=null) {

view =mFactory.onCreateView(name, context, attrs);

}else {

view =null;

}

if (view ==null &&mPrivateFactory !=null) {

view =mPrivateFactory.onCreateView(parent, name, context, attrs);

}

if (view ==null) {

final Object lastContext =mConstructorArgs[0];

mConstructorArgs[0] = context;

try {

if (-1 == name.indexOf('.')) {//判断是否是自定义View

view = onCreateView(parent, name, attrs);

}else {

view = createView(name,null, attrs);

}

}finally {

mConstructorArgs[0] = lastContext;

}

}

return view;

}

通过分析上面代码可以看出Factory2如果不为空那么就调用Factory2的方法创建View

否者就使用onCreateView()方法创建View

android换肤哪个简单,Android一键换肤功能实现

那么如果我们给定一个Factory那么我们就可以监视所有的view

View设置资源文件的流程如图所示

android换肤哪个简单,Android一键换肤功能实现

当我们拿到当前View的资源名称时就会先去插件中的资源文件里找。

这就是换肤的原理

android换肤哪个简单,Android一键换肤功能实现

加载外部Apk资源文件

拿到资源文件相信剩下的大家就知道怎么玩了

代码已经上传给 github,欢迎大家一起讨论研究

使用方式

android换肤哪个简单,Android一键换肤功能实现

初始化

android换肤哪个简单,Android一键换肤功能实现

使用

皮肤包就是一个只有资源文件的Apk

大家可以看一下我其他文章哦