本文作者
作者:孙先森Blog
链接:
https://juejin.cn/post/7154205345462616077
本文由作者授权发布。
Android 干货分享:插件化换肤原理(1)—— 布局加载过程、View创建流程、Resources 浅析
https://juejin.cn/post/7153807668988084237
Android 干货分享:插件化换肤原理(2)—— 实现思路、主流框架分析
https://juejin.cn/post/7154205345462616077
https://github.com/ximsfei/Android-skin-support
interface SkinSupportable {
fun applySkin() // 换肤方法
}
class SkinButton @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : Button(context, attrs), SkinSupportable {
// 换肤方法 在这里写换肤的逻辑
override fun applySkin() {
// 皮肤包路径
val skinApkPath = "xxx/skin/skin.apk"
// 获取皮肤包的 packageInfo
val pInfo = context.packageManager.getPackageArchiveInfo(skinApkPath, PackageManager.GET_ACTIVITIES)
pInfo.applicationInfo.sourceDir = skinApkPath
pInfo.applicationInfo.publicSourceDir = skinApkPath
// 获取皮肤包的 Resources
val skinRes = context.packageManager.getResourcesForApplication(pInfo.applicationInfo)
// 获取 app 的 Resources 用于获取 displayMetrics、configuration
val res = context.resources
// 构造出新的皮肤包 Resources;skinRes.assets 是皮肤包的 AssetManager
val newRes = Resources(skinRes.assets, res.displayMetrics, res.configuration)
// 当前按钮默认背景色
val defaultResId = R.color.colorPrimary
val resName = res.getResourceEntryName(defaultResId) // name 用于去皮肤包中寻找资源
val resType = res.getResourceTypeName(defaultResId) // type
// 从皮肤包中寻找同名资源的 id
val skinResId = newRes.getIdentifier(resName, resType, pInfo.packageName)
// 通过资源 id 在皮肤包的 Resources 中寻找 color
val skinColor = newRes.getColor(newColorId)
setBackgroundColor(newColor)
}
}仿照 AppCompatActivity 的思路在 onCreate 替换 Factory2:
// 用于记录换肤 View
val skinViews = mutableListOf<SkinSupportable>()
override fun onCreate(savedInstanceState: Bundle?) {
LayoutInflater.from(this).factory2 = object : LayoutInflater.Factory2 {
override fun onCreateView(name: String, context: Context, attrs: AttributeSet): View? {
return onCreateView(null, name, context, attrs)
}
override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {
if (name == "Button"){ // 如果是 Button 就替换为我们自己的 SkinButton
val view = SkinButton(context, attrs)
skinViews.add(view) //记录
return view
}
return null
}
}
// 要在调用父类 onCreate 方法前对 Factory2 进行替换
super.onCreate(savedInstanceState)
}
// 换肤按钮
bnSkin.setOnClickListener {
for (view in skinViews) {
view.applySkin() // 换肤
}
}
private boolean mFactorySet; // false
public void setFactory2(Factory2 factory) {
if (mFactorySet) { // ture 则直接
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
// ...
mFactorySet = true; // 设置一次 factory2 后直接设置为 true
if (mFactory == null) {
mFactory = mFactory2 = factory;
}
// ...
}
根据源码可以看出,设置一次 mFactory2 后,再次设置会直接抛出异常。在第一篇的分析中,AppCompatActivity 已经在 onCreate 中调用 setFactory2 了,所以最好还是用反射来修改 mFactory2,防止闪退。
上面的代码是非常简陋的实现,仅仅是对这个换肤思路的测试,我在实现换肤功能时借鉴了 Android-skin-support 开源库。下面根据上面所说的思路,来看一下开源库中的具体实现。
https://github.com/ximsfei/Android-skin-support
GitHub:
https://github.com/ximsfei/Android-skin-support
public class SkinActivityLifecycle implements Application.ActivityLifecycleCallbacks {
// 初始化
public static SkinActivityLifecycle init(Application application) {
if (sInstance == null) {
synchronized (SkinActivityLifecycle.class) {
if (sInstance == null) {
sInstance = new SkinActivityLifecycle(application); // 构造
}
}
}
return sInstance;
}
// 构造方法
private SkinActivityLifecycle(Application application) {
application.registerActivityLifecycleCallbacks(this); // Application 注册回调
installLayoutFactory(application); // 设置 Factory2
SkinCompatManager.getInstance().addObserver(getObserver(application));
}
private void installLayoutFactory(Context context) {
try {
LayoutInflater layoutInflater = LayoutInflater.from(context);
// 另写了个工具类 LayoutInflaterCompat 来设置
// getSkinDelegate(context) 获取自定义的 Factory2
LayoutInflaterCompat.setFactory2(layoutInflater, getSkinDelegate(context));
} catch (Throwable e) {
Slog.i("SkinActivity", "A factory has already been set on this LayoutInflater");
}
}
}
public static void setFactory2(
LayoutInflater inflater, LayoutInflater.Factory2 factory) {
inflater.setFactory2(factory); // 直接设置
if (Build.VERSION.SDK_INT < 21) { // api 21 以下利用反射修改
final LayoutInflater.Factory f = inflater.getFactory();
if (f instanceof LayoutInflater.Factory2) {
forceSetFactory2(inflater, (LayoutInflater.Factory2) f);
} else {
forceSetFactory2(inflater, factory);
}
}
}
// 反射修改
private static void forceSetFactory2(LayoutInflater inflater, LayoutInflater.Factory2 factory) {
// ...
sLayoutInflaterFactory2Field = LayoutInflater.class.getDeclaredField("mFactory2");
sLayoutInflaterFactory2Field.setAccessible(true);
// ...
sLayoutInflaterFactory2Field.set(inflater, factory);
// ...
}
private SkinCompatDelegate getSkinDelegate(Context context) {
if (mSkinDelegateMap == null) { // 作者做了很多优化
mSkinDelegateMap = new WeakHashMap<>();
}
SkinCompatDelegate mSkinDelegate = mSkinDelegateMap.get(context);
if (mSkinDelegate == null) {
mSkinDelegate = SkinCompatDelegate.create(context); // 新建
mSkinDelegateMap.put(context, mSkinDelegate); // 缓存起来
}
return mSkinDelegate;
}
public static SkinCompatDelegate create(Context context) {
return new SkinCompatDelegate(context);
}
// 用弱引用保存需要换肤的 View 防止内存泄漏
private List<WeakReference<SkinCompatSupportable>> mSkinHelpers = new CopyOnWriteArrayList<>();
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
// 创建View
View view = createView(parent, name, context, attrs);
// ...
// 将换肤 View 保存起来
if (view instanceof SkinCompatSupportable) {
mSkinHelpers.add(new WeakReference<>((SkinCompatSupportable) view));
}
return view;
}
// 创建 View 方法
public final View createView(View parent, final String name, @NonNull Context context, @NonNull AttributeSet attrs) {
// 给开发者们开放的 自定义 Inflater 这个已经标记删除
View view = createViewFromHackInflater(context, name, attrs);
if (view == null) { // 给开发者们开放的 自定义 Inflater
view = createViewFromInflater(context, name, attrs);
}
if (view == null) { // 反射创建
view = createViewFromTag(context, name, attrs);
}
// ...
return view;
}
public Resources getSkinResources(String skinPkgPath) {
PackageInfo packageInfo = mAppContext.getPackageManager().getPackageArchiveInfo(skinPkgPath, 0);
packageInfo.applicationInfo.sourceDir = skinPkgPath;
packageInfo.applicationInfo.publicSourceDir = skinPkgPath;
Resources res = mAppContext.getPackageManager().getResourcesForApplication(packageInfo.applicationInfo);
Resources superRes = mAppContext.getResources();
return new Resources(res.getAssets(), superRes.getDisplayMetrics(), superRes.getConfiguration());
}
public int getTargetResId(Context context, int resId) {
// 获取 name
String resName = null;
if (mStrategy != null) {
resName = mStrategy.getTargetResourceEntryName(context, mSkinName, resId);
}
if (TextUtils.isEmpty(resName)) {
resName = context.getResources().getResourceEntryName(resId);
}
// 获取 type
String type = context.getResources().getResourceTypeName(resId);
// mResources 就是 皮肤包的 Resources
// 查找皮肤包的同名同类型资源 id
return mResources.getIdentifier(resName, type, mSkinPkgName);
}
最后推荐一下我做的网站,玩Android: wanandroid.com ,包含详尽的知识体系、好用的工具,还有本公众号文章合集,欢迎体验和收藏!
推荐阅读:
扫一扫 关注我的公众号
如果你想要跟大家分享你的文章,欢迎投稿~
┏(^0^)┛明天见!