Android换肤原理和Android-Skin-Loader框架解析

移动开发 Android
Android换肤技术已经是很久之前就已经被成熟使用的技术了,然而我最近才在学习和接触热修复的时候才看到。在看了一些换肤的方法之后,并且对市面上比较认可的Android-Skin-Loader换肤框架的源码进行了分析总结。再次记录一下祭奠自己逝去的时间。

Android换肤技术已经是很久之前就已经被成熟使用的技术了,然而我最近才在学习和接触热修复的时候才看到。在看了一些换肤的方法之后,并且对市面上比较认可的Android-Skin-Loader换肤框架的源码进行了分析总结。再次记录一下祭奠自己逝去的时间。

Android换肤原理和Android-Skin-Loader框架解析

换肤介绍

换肤本质上是对资源的一中替换包括、字体、颜色、背景、图片、大小等等。当然这些我们都有成熟的api可以通过控制代码逻辑做到。比如View的修改背景颜色 setBackgroundColor ,TextView的 setTextSize 修改字体等等。但是作为程序员我们怎么能忍受对每个页面的每个元素一个行行代码做换肤处理呢?我们需要用最少的代码实现最容易维护和使用效果***(动态切换,及时生效)的换肤框架。

换肤方式一:切换使用主题Theme

使用相同的资源id,但在不同的Theme下边自定义不同的资源。我们通过主动切换到不同的Theme从而切换界面元素创建时使用的资源。这种方案的代码量不多发,而且有个很明显的缺点不支持已经创建界面的换肤,必须重新加载界面元素。 GitHub Demo

换肤方式二:加载资源包

加载资源包是各种应用程序都在使用的换肤方法,例如我们最常用的输入法皮肤、浏览器皮肤等等。我们可以将皮肤的资源文件放入安装包内部,也可以进行下载缓存到磁盘上。Android的应用程序可以使用这种方式进行换肤。GitHub上面有一个start非常高的换肤框架 Android-Skin-Loader 就是通过加载资源包对app进行换肤。对这个框架的分析这个也是这篇文章主要的讲述内容。

对比一下发现切换Theme可以进行小幅度的换肤设置(比如某个自定义组件的主题),而如果我们想要对整个app做主题切换那么通过加载资源包的这种方式目前应该说是比较好的了。

Android换肤知识点

换肤相应的API

我们先来看一下Android提供的一些基本的api,通过使用这些api可以在App内部进行资源对象的替换。

 

  1. public class Resources{ 
  2.     public String getString(int id)throws NotFoundException { 
  3.         CharSequence res = mAssets.getResourceText(id); 
  4.         if (res != null) { 
  5.             return res; 
  6.         } 
  7.         throw new NotFoundException("String resource ID #0x" 
  8.                                     + Integer.toHexString(id)); 
  9.     } 
  10.     public Drawable getDrawable(int id)throws NotFoundException { 
  11.         /********部分代码省略*******/ 
  12.     } 
  13.     public int getColor(int id)throws NotFoundException {{ 
  14.         /********部分代码省略*******/ 
  15.     } 
  16.     /********部分代码省略*******/ 

这个是我们常用的Resources类的api,我们通常可以使用在资源文件中定义的 @+id String类型,然后在编译出的R.java中对应的资源文件生产的id(int类型),从而通过这个id(int类型)调用Resources提供的这些api获取到对应的资源对象。这个在同一个app下没有任何问题,但是在皮肤包中我们怎么获取这个id值呢。

 

  1. public class Resources{ 
  2.     /********部分代码省略*******/ 
  3.     /** 
  4. * 通过给的资源名称返回一个资源的标识id。 
  5. *@paramname 描述资源的名称 
  6. *@paramdefType 资源的类型 
  7. *@paramdefPackage 包名 
  8. *@return返回资源id,0标识未找到该资源 
  9. */ 
  10.     public int getIdentifier(String name, String defType, String defPackage){ 
  11.         if (name == null) { 
  12.             throw new NullPointerException("name is null"); 
  13.         } 
  14.         try { 
  15.             return Integer.parseInt(name); 
  16.         } catch (Exception e) { 
  17.             // Ignore 
  18.         } 
  19.         return mAssets.getResourceIdentifier(name, defType, defPackage); 
  20.     } 

Resources提供了可以通过 @+id 、Type、PackageName这三个参数就可以在AssetManager中寻找相应的PackageName中有没有Type类型并且id值都能与参数对应上的id,进行返回。然后我们可以通过这个id再调用Resource的获取资源的api就可以得到相应的资源。

这里我们需要注意的一点是 getIdentifier(String name, String defType, String defPackage) 方法和 getString(int id) 方法所调用Resources对象的mAssets对象必须是同一个,并且包含有PackageName这个资源包。

AssetManager构造

怎么构造一个包含特定packageName资源的AssetManager对象实例呢?

 

  1. public final class AssetManagerimplements AutoCloseable{ 
  2.     /********部分代码省略*******/ 
  3.     /** 
  4. Create a new AssetManager containing only the basic system assets. 
  5. * Applications will not generally use this method, instead retrieving the 
  6. * appropriate asset manager with {@linkResources#getAssets}. Not for 
  7. * use by applications. 
  8. * {@hide} 
  9. */ 
  10.     public AssetManager(){ 
  11.         synchronized (this) { 
  12.             if (DEBUG_REFS) { 
  13.                 mNumRefs = 0; 
  14.                 incRefsLocked(this.hashCode()); 
  15.             } 
  16.             init(false); 
  17.             if (localLOGV) Log.v(TAG, "New asset manager: " + this); 
  18.             ensureSystemAssets(); 
  19.         } 
  20.     } 

从AssetManager的构造函数来看有 {@hide} 的朱姐,所以在其他类里面是直接创建AssetManager实例。但是不要忘记Java中还有反射机制可以创建类对象。

  1. AssetManager assetManager = AssetManager.class.newInstance(); 

让创建的assetManager包含特定的PackageName的资源信息,怎么办?我们在AssetManager中找到相应的api可以调用。

 

  1. public final class AssetManagerimplements AutoCloseable{ 
  2.     /********部分代码省略*******/ 
  3.     /** 
  4. Add an additional set of assets to the asset manager. This can be 
  5. * either a directory or ZIP file. Not for use by applications. Returns 
  6. * the cookie of the added asset, or 0 on failure. 
  7. * {@hide} 
  8. */ 
  9.     public final int addAssetPath(String path){ 
  10.         synchronized (this) { 
  11.             int res = addAssetPathNative(path); 
  12.             if (mStringBlocks != null) { 
  13.                 makeStringBlocks(mStringBlocks); 
  14.             } 
  15.             return res; 
  16.         } 
  17.     } 

同样改方法也不支持外部调用,我们只能通过反射的方法来调用。

 

  1. /** 
  2. * apk路径 
  3. */ 
  4. String apkPath = Environment.getExternalStorageDirectory()+"/skin.apk"
  5. AssetManager assetManager = null
  6. try { 
  7.     AssetManager assetManager = AssetManager.class.newInstance(); 
  8.     AssetManager.class.getDeclaredMethod("addAssetPath", String.class).invoke(assetManager, apkPath); 
  9. } catch (Throwable th) { 
  10.     th.printStackTrace(); 

至此我们可以构造属于自己换肤的Resources了。

换肤Resources构造

 

  1. public Resources getSkinResources(Context context){ 
  2.     /** 
  3. * 插件apk路径 
  4. */ 
  5.     String apkPath = Environment.getExternalStorageDirectory()+"/skin.apk"
  6.     AssetManager assetManager = null
  7.     try { 
  8.         AssetManager assetManager = AssetManager.class.newInstance(); 
  9.         AssetManager.class.getDeclaredMethod("addAssetPath", String.class).invoke(assetManager, apkPath); 
  10.     } catch (Throwable th) { 
  11.         th.printStackTrace(); 
  12.     } 
  13.     return new Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration()); 

使用资源包中的资源换肤

我们将上述所有的代码组合在一起就可以实现,使用资源包中的资源对app进行换肤。

 

  1. public Resources getSkinResources(Context context){ 
  2.     /** 
  3. * 插件apk路径 
  4. */ 
  5.     String apkPath = Environment.getExternalStorageDirectory()+"/skin.apk"
  6.     AssetManager assetManager = null
  7.     try { 
  8.         AssetManager assetManager = AssetManager.class.newInstance(); 
  9.         AssetManager.class.getDeclaredMethod("addAssetPath", String.class).invoke(assetManager, apkPath); 
  10.     } catch (Throwable th) { 
  11.         th.printStackTrace(); 
  12.     } 
  13.     return new Resources(assetManager, context.getResources().getDisplayMetrics(), context.getResources().getConfiguration()); 
  14. @Override 
  15. protected void onCreate(Bundle savedInstanceState){ 
  16.     super.onCreate(savedInstanceState); 
  17.     setContentView(R.layout.activity_main); 
  18.     ImageView imageView = (ImageView) findViewById(R.id.imageView); 
  19.     TextView textView = (TextView) findViewById(R.id.text); 
  20.     /** 
  21. * 插件资源对象 
  22. */ 
  23.     Resources resources = getSkinResources(this); 
  24.     /** 
  25. * 获取图片资源 
  26. */ 
  27.     Drawable drawable = resources.getDrawable(resources.getIdentifier("night_icon""drawable","com.tzx.skin")); 
  28.     /** 
  29. * 获取文本资源 
  30. */ 
  31.     int color = resources.getColor(resources.getIdentifier("night_color","color","com.tzx.skin")); 
  32.  
  33.     imageView.setImageDrawable(drawable); 
  34.     textView.setText(text); 
  35.  

通过上述介绍,我们可以简单的对当前页面进行换肤了。但是想要做出一个一个成熟换肤框架那么仅仅这些还是不够的,提高一下我们的思维高度,如果我们在View创建的时候就直接使用皮肤资源包中的资源文件,那么这无疑就使换肤更加的简单已维护。

LayoutInflater.Factory

看过我前一篇 遇见LayoutInflater&Factory 文章的这部分可以省略掉.

很幸运Android给我们在View生产的时候做修改提供了法门。

 

  1. public abstract class LayoutInflater{ 
  2.     /***部分代码省略****/ 
  3.     public interface Factory{ 
  4.         public View onCreateView(String name, Context context, AttributeSet attrs); 
  5.     } 
  6.  
  7.     public interface Factory2extends Factory{ 
  8.         public View onCreateView(View parent, String name, Context context, AttributeSet attrs); 
  9.     } 
  10.     /***部分代码省略****/ 

我们可以给当前的页面的Window对象在创建的时候设置Factory,那么在Window中的View进行创建的时候就会先通过自己设置的Factory进行创建。Factory使用方式和相关注意事项请移位到 遇见LayoutInflater&Factory ,关于Factory的相关知识点尽在其中。

Android-Skin-Loader解析

初始化

初始化换肤框架,导入需要换肤的资源包(当前为一个apk文件,其中只有资源文件)。

 

  1. public class SkinApplicationextends Application{ 
  2.     public void onCreate(){ 
  3.         super.onCreate(); 
  4.         initSkinLoader(); 
  5.     } 
  6.     /** 
  7. * Must call init first 
  8. */ 
  9.     private void initSkinLoader(){ 
  10.         SkinManager.getInstance().init(this); 
  11.         SkinManager.getInstance().load(); 
  12.     } 

构造换肤对象

导入需要换肤的资源包,并构造换肤的Resources实例。

 

  1. /** 
  2. Load resources from apk in asyc task 
  3. *@paramskinPackagePath path of skin apk 
  4. *@paramcallback callback to notify user 
  5. */ 
  6. public void load(String skinPackagePath,final ILoaderListener callback){ 
  7.      
  8.     new AsyncTask<String, Void, Resources>() { 
  9.  
  10.         protected void onPreExecute(){ 
  11.             if (callback != null) { 
  12.                 callback.onStart(); 
  13.             } 
  14.         }; 
  15.  
  16.         @Override 
  17.         protected Resources doInBackground(String... params){ 
  18.             try { 
  19.                 if (params.length == 1) { 
  20.                     String skinPkgPath = params[0]; 
  21.                      
  22.                     File file = new File(skinPkgPath);  
  23.                     if(file == null || !file.exists()){ 
  24.                         return null
  25.                     } 
  26.                      
  27.                     PackageManager mPm = context.getPackageManager(); 
  28.                     //检索程序外的一个安装包文件 
  29.                     PackageInfo mInfo = mPm.getPackageArchiveInfo(skinPkgPath, PackageManager.GET_ACTIVITIES); 
  30.                     //获取安装包报名 
  31.                     skinPackageName = mInfo.packageName; 
  32.                     //构建换肤的AssetManager实例 
  33.                     AssetManager assetManager = AssetManager.class.newInstance(); 
  34.                     Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class); 
  35.                     addAssetPath.invoke(assetManager, skinPkgPath); 
  36.                     //构建换肤的Resources实例 
  37.                     Resources superRes = context.getResources(); 
  38.                     Resources skinResource = new Resources(assetManager,superRes.getDisplayMetrics(),superRes.getConfiguration()); 
  39.                     //存储当前皮肤路径 
  40.                     SkinConfig.saveSkinPath(context, skinPkgPath); 
  41.                      
  42.                     skinPath = skinPkgPath; 
  43.                     isDefaultSkin = false
  44.                     return skinResource; 
  45.                 } 
  46.                 return null
  47.             } catch (Exception e) { 
  48.                 e.printStackTrace(); 
  49.                 return null
  50.             } 
  51.         }; 
  52.  
  53.         protected void onPostExecute(Resources result){ 
  54.             mResources = result; 
  55.  
  56.             if (mResources != null) { 
  57.                 if (callback != null) callback.onSuccess(); 
  58.                 //更新多有可换肤的界面 
  59.                 notifySkinUpdate(); 
  60.             }else
  61.                 isDefaultSkin = true
  62.                 if (callback != null) callback.onFailed(); 
  63.             } 
  64.         }; 
  65.  
  66.     }.execute(skinPackagePath); 

定义基类

换肤页面的基类的通用代码实现基本换肤功能。

 

  1. public class BaseFragmentActivityextends FragmentActivityimplements ISkinUpdate,IDynamicNewView{ 
  2.      
  3.     /***部分代码省略****/ 
  4.      
  5.     //自定义LayoutInflater.Factory 
  6.     private SkinInflaterFactory mSkinInflaterFactory; 
  7.      
  8.     @Override 
  9.     protected void onCreate(Bundle savedInstanceState){ 
  10.         super.onCreate(savedInstanceState); 
  11.      
  12.         try { 
  13.             //设置LayoutInflater的mFactorySet为true,表示还未设置mFactory,否则会抛出异常。 
  14.             Field field = LayoutInflater.class.getDeclaredField("mFactorySet"); 
  15.             field.setAccessible(true); 
  16.             field.setBoolean(getLayoutInflater(), false); 
  17.             //设置LayoutInflater的MFactory 
  18.             mSkinInflaterFactory = new SkinInflaterFactory(); 
  19.             getLayoutInflater().setFactory(mSkinInflaterFactory); 
  20.  
  21.         } catch (NoSuchFieldException e) { 
  22.             e.printStackTrace(); 
  23.         } catch (IllegalArgumentException e) { 
  24.             e.printStackTrace(); 
  25.         } catch (IllegalAccessException e) { 
  26.             e.printStackTrace(); 
  27.         }  
  28.          
  29.     } 
  30.  
  31.     @Override 
  32.     protected void onResume(){ 
  33.         super.onResume(); 
  34.         //注册皮肤管理对象 
  35.         SkinManager.getInstance().attach(this); 
  36.     } 
  37.      
  38.     @Override 
  39.     protected void onDestroy(){ 
  40.         super.onDestroy(); 
  41.         //反注册皮肤管理对象 
  42.         SkinManager.getInstance().detach(this); 
  43.     } 
  44.     /***部分代码省略****/ 

SkinInflaterFactory

  • SkinInflaterFactory进行View的创建并对View进行换肤。

构造View

 

  1. public class SkinInflaterFactoryimplements Factory{ 
  2.     /***部分代码省略****/ 
  3.     public View onCreateView(String name, Context context, AttributeSet attrs){ 
  4.         //读取View的skin:enable属性,false为不需要换肤 
  5.         // if this is NOT enable to be skined , simplly skip it 
  6.         boolean isSkinEnable = attrs.getAttributeBooleanValue(SkinConfig.NAMESPACE, SkinConfig.ATTR_SKIN_ENABLE, false); 
  7.         if (!isSkinEnable){ 
  8.                 return null
  9.         } 
  10.         //创建View 
  11.         View view = createView(context, name, attrs); 
  12.         if (view == null){ 
  13.             return null
  14.         } 
  15.         //如果View创建成功,对View进行换肤 
  16.         parseSkinAttr(context, attrs, view); 
  17.         return view
  18.     } 
  19.     //创建View,类比可以查看LayoutInflater的createViewFromTag方法 
  20.     private View createView(Context context, String name, AttributeSet attrs){ 
  21.         View view = null
  22.         try { 
  23.             if (-1 == name.indexOf('.')){ 
  24.                 if ("View".equals(name)) { 
  25.                     view = LayoutInflater.from(context).createView(name"android.view.", attrs); 
  26.                 }  
  27.                 if (view == null) { 
  28.                     view = LayoutInflater.from(context).createView(name"android.widget.", attrs); 
  29.                 }  
  30.                 if (view == null) { 
  31.                     view = LayoutInflater.from(context).createView(name"android.webkit.", attrs); 
  32.                 }  
  33.             }else { 
  34.                 view = LayoutInflater.from(context).createView(namenull, attrs); 
  35.             } 
  36.  
  37.             L.i("about to create " + name); 
  38.  
  39.         } catch (Exception e) {  
  40.             L.e("error while create 【" + name + "】 : " + e.getMessage()); 
  41.             view = null
  42.         } 
  43.         return view
  44.     } 

对生产的View进行换肤

 

  1. public class SkinInflaterFactoryimplements Factory{ 
  2.     //存储当前Activity中的需要换肤的View 
  3.     private List<SkinItem> mSkinItems = new ArrayList<SkinItem>(); 
  4.     /***部分代码省略****/ 
  5.     private void parseSkinAttr(Context context, AttributeSet attrs, View view){ 
  6.         //当前View的所有属性标签 
  7.         List<SkinAttr> viewAttrs = new ArrayList<SkinAttr>(); 
  8.          
  9.         for (int i = 0; i < attrs.getAttributeCount(); i++){ 
  10.             String attrName = attrs.getAttributeName(i); 
  11.             String attrValue = attrs.getAttributeValue(i); 
  12.              
  13.             if(!AttrFactory.isSupportedAttr(attrName)){ 
  14.                 continue
  15.             } 
  16.             //过滤view属性标签中属性的value的值为引用类型 
  17.             if(attrValue.startsWith("@")){ 
  18.                 try { 
  19.                     int id = Integer.parseInt(attrValue.substring(1)); 
  20.                     String entryName = context.getResources().getResourceEntryName(id); 
  21.                     String typeName = context.getResources().getResourceTypeName(id); 
  22.                     //构造SkinAttr实例,attrname,id,entryName,typeName 
  23.                     //属性的名称(background)、属性的id值(int类型),属性的id值(@+id,string类型),属性的值类型(color) 
  24.                     SkinAttr mSkinAttr = AttrFactory.get(attrName, id, entryName, typeName); 
  25.                     if (mSkinAttr != null) { 
  26.                         viewAttrs.add(mSkinAttr); 
  27.                     } 
  28.                 } catch (NumberFormatException e) { 
  29.                     e.printStackTrace(); 
  30.                 } catch (NotFoundException e) { 
  31.                     e.printStackTrace(); 
  32.                 } 
  33.             } 
  34.         } 
  35.         //如果当前View需要换肤,那么添加在mSkinItems中 
  36.         if(!ListUtils.isEmpty(viewAttrs)){ 
  37.             SkinItem skinItem = new SkinItem(); 
  38.             skinItem.view = view
  39.             skinItem.attrs = viewAttrs; 
  40.  
  41.             mSkinItems.add(skinItem); 
  42.             //是否是使用外部皮肤进行换肤 
  43.             if(SkinManager.getInstance().isExternalSkin()){ 
  44.                 skinItem.apply(); 
  45.             } 
  46.         } 
  47.     } 

资源获取

通过当前的资源id,找到对应的资源name。再从皮肤包中找到该资源name所对应的资源id。

 

  1. public class SkinManagerimplements ISkinLoader{ 
  2.     /***部分代码省略****/ 
  3.     public int getColor(int resId){ 
  4.         int originColor = context.getResources().getColor(resId); 
  5.         //是否没有下载皮肤或者当前使用默认皮肤 
  6.         if(mResources == null || isDefaultSkin){ 
  7.             return originColor; 
  8.         } 
  9.         //根据resId值获取对应的xml的的@+id的String类型的值 
  10.         String resName = context.getResources().getResourceEntryName(resId); 
  11.         //更具resName在皮肤包的mResources中获取对应的resId 
  12.         int trueResId = mResources.getIdentifier(resName, "color", skinPackageName); 
  13.         int trueColor = 0; 
  14.         try{ 
  15.             //根据resId获取对应的资源value 
  16.             trueColor = mResources.getColor(trueResId); 
  17.         }catch(NotFoundException e){ 
  18.             e.printStackTrace(); 
  19.             trueColor = originColor; 
  20.         } 
  21.          
  22.         return trueColor; 
  23.     } 
  24.     public Drawable getDrawable(int resId){...} 

其他

除此之外再增加以下对于皮肤的管理api(下载、监听回调、应用、取消、异常处理、扩展模块等等)。

总结

换肤就是这么简单~!~!

文章到这里就全部讲述完啦,若有其他需要交流的可以留言哦~!~!

责任编辑:未丽燕 来源: 下雨天要逛街
相关推荐

2017-01-11 19:05:45

AndroidAndroid Loa详解

2010-01-28 17:18:08

Android模拟器s

2013-12-06 10:35:28

Android游戏引擎libgdx教程

2010-02-05 18:04:36

Android程序框架

2010-03-02 14:24:00

Android应用程序

2021-08-20 07:53:07

Android动态换肤

2024-01-18 08:31:22

go实现gorm框架

2021-09-09 06:55:43

AndroidViewDragHel原理

2017-09-30 16:06:28

代码注解分析

2021-05-31 05:36:43

WebpackJavaScript 前端

2013-07-05 14:41:27

Android

2017-02-21 12:20:20

Android事件分发机制实例解析

2013-07-29 16:22:21

Android缓存框架

2017-05-18 15:02:36

AndroidGC原理JVM内存回收

2009-10-27 11:16:20

VB.NET应用框架

2013-06-08 11:04:18

Android开发Pull解析XMLAndroid XML

2013-11-26 16:32:47

Android关机移动编程

2011-08-31 13:27:52

AndroidPhoneGap

2018-12-13 10:37:13

Android开发框架

2016-12-02 20:43:34

Android动态加载DL框架
点赞
收藏

51CTO技术栈公众号