美文网首页
Android动态皮肤学习总结

Android动态皮肤学习总结

作者: 羽寂 | 来源:发表于2020-02-03 18:14 被阅读0次

    背景

    目前很多app都具有换肤功能,用户可以根据需要切换不同的皮肤,为使我们的App支持换肤功能,给用户提供更好的体验,在这里对换肤原理进行研究总结,并选择一个合适的换肤解决方案。

    换肤介绍

    App换肤主要涉及的有页面中文字的颜色、控件的背景颜色、一些图片资源和主题颜色等资源。

    为了实现换肤资源不与原项目混淆,尽量降低风险,可以将这些资源封装在一个独立的Apk资源文件中。在App运行时,主程序动态的从Apk皮肤包中读取相应的资源,无需Acitvity重启即可实现皮肤的实时更换,皮肤包与原安装包相分离,从而实现插件式换肤。

    换肤原理

    基本原理:

    1.给需要更换皮肤的view打上tag (ActivityLifecycleCallbacks全局监听生命周期)

    2.生成皮肤包(皮肤资源名称和项目中一致)

    3.使用AssetManager加载外部皮肤包

    4.遍历带tag的view设置皮肤

    1. 如何加载皮肤资源文件

    使用插件式换肤,皮肤资源肯定不会在被封装到主工程中,要怎么加载外部的皮肤资源呢?

    先看下 Apk 的打包流程

    img
    1.R文件的生成

    R文件是一个Java文件,通过R文件我们就可以找到对应的资源。R文件就像一张映射表,帮助我们找到资源文件。

    2.资源文件的打包生成

    资源文件经过压缩打包,生成 resources 文件,通过R文件找到里面保存的对映的资源文件。在 App 内部,我们一般通过下面代码,获取资源:

    context.getResource.getString(R.string.hello);
    context.getResource.getColor(R.color.black);
    context.getResource.getDrawable(R.drawable.splash);
    

    这个获取 App 内部的资源代码,能为我们加载皮肤资源提供什么思路吗?加载外部资源的 Resources 能通过类似的思路实现吗? 我们查看下 Resources 类的源码,发现 Resources 的构造函数

    public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) {
          this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO);
      }
    

    这里关键是第一个参数如何获取,第二和第三个参数可以通过 Activity 获取到。我们再去看下 AssetManager 的代码,同时会发现下面的这个

    /**
         * Add an additional set of assets to the asset manager.  This can be
         * either a directory or ZIP file.  Not for use by applications.  Returns
         * the cookie of the added asset, or 0 on failure.
         * {@hide}
         */
      public final int addAssetPath(String path) {
            synchronized (this) {
                int res = addAssetPathNative(path);
                makeStringBlocks(mStringBlocks);
                return res;
            }
        }
    

    AssetManager 可以加载一个zip 格式的压缩包,而 Apk 文件不就是一个 压缩包吗。我们通过反射的方法,拿到 AssetManager,加载 Apk 内部的资源,获取到 Resources 对象,这样再想办法,把 R文件里面保存的ID获取到,这样既可以拿到对应的资源文件了。理论上我们的思路时成立的。

    我们看下,如何通过代码获取 Resources 对象。

    //通过反射的方法调用AssetManager的addAssetPath方法,通过此方法去设置皮肤包所在的路径
    AssetManager assetManager = AssetManager.class.newInstance();
    Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
    addAssetPath.invoke(assetManager, skinPkgPath);
    
    //通过创建一个resource来获取皮肤包里的资源 
    Resources superRes = context.getResources();
    Resources skinResource = new Resources(assetManager,superRes.getDisplayMetrics(),superRes.getConfiguration());
    

    2. 如何标记需要换肤的View

    找到资源文件之后,我们要接着标记需要换肤的 View 。

    找到需要换肤的 View?

    怎么寻找哪些是我们要换肤的 View 呢? 我们还是从 View 的创建时机寻找机会。我们添加一个布局文件时,会使用 LayoutInflater的 Inflater方法,我们看下这个方法是怎么讲一个View添加到Activity 中的。 LayoutInflater 中有个接口

    public interface Factory {
            /**
             * Hook you can supply that is called when inflating from a LayoutInflater.
             * You can use this to customize the tag names available in your XML
             * layout files.
             *
             * 当你通过LayoutInflater加载一个布局时,你可以在此处进行hook操作。
             * 你可以使用此方法去设置tag名字在你的xml布局文件上
             * <p>
             * Note that it is good practice to prefix these custom names with your
             * package (i.e., com.coolcompany.apps) to avoid conflicts with system
             * names.
             *
             * @param name Tag name to be inflated.  通过tag名称被加载的view
             * @param context The context the view is being created in.
             * @param attrs Inflation attributes as specified in XML file.
             *
             * @return View Newly created view. Return null for the default
             *         behavior.
             */
            public View onCreateView(String name, Context context, AttributeSet attrs);
        }
    

    根据这里的注释描述,我们可以自己实现这个接口,在 onCreateView 方法中选择我们需要标记的View,根据 AttributeSet 值,过滤不需要关注的View。

    标记 View 与对应的资源

    我们在 View 创建时,通过过滤 Attribute 属性,找到我们要标记的 View ,下面我们就把这些View的属性记下来

    for (int i = 0; i < attrs.getAttributeCount(); i++){
                String attrName = attrs.getAttributeName(i);
                String attrValue = attrs.getAttributeValue(i);
                if(!AttrFactory.isSupportedAttr(attrName)){
                    continue;
                } 
                if(attrValue.startsWith("@")){
                    try {
                        int id = Integer.parseInt(attrValue.substring(1));
                        String entryName = context.getResources().getResourceEntryName(id);
                        String typeName = context.getResources().getResourceTypeName(id);
                        SkinAttr mSkinAttr = AttrFactory.get(attrName, id, entryName, typeName);
                        if (mSkinAttr != null) {
                            viewAttrs.add(mSkinAttr);
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    } catch (NotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
    

    然后把这些 View 和属性值,一起封装保存起来

    if(!ListUtils.isEmpty(viewAttrs)){
                SkinItem skinItem = new SkinItem();
                skinItem.view = view;
                skinItem.attrs = viewAttrs;
                mSkinItems.add(skinItem);
                if(SkinManager.getInstance().isExternalSkin()){
                    skinItem.apply();
                }
        }
    

    3. 如何做到及时更新UI

    由于我们把需要更新的View 以及属性值都保存起来了,更新的时候只要把他们取出来遍历一遍即可。

    @Override
    public void onThemeUpdate() {
         if(!isResponseOnSkinChanging){
              return;
         }
         mSkinInflaterFactory.applySkin();
     }
    //applySkin 的具体实现
    public void applySkin(){
         if(ListUtils.isEmpty(mSkinItems)){
             return;
          }  
         for(SkinItem si : mSkinItems){
              if(si.view == null){
                  continue;
             }
               si.apply();
         }
     }
    

    4. 皮肤包的生成

    其实很简单,就是我们重新建立一个项目(这个项目里面的资源名字和需要换肤的项目的资源名字是对应的就可以),记住我们是通过名字去获取资源,不是id

    1. 新建工程project

    2. 将换肤的资源文件添加到res文件下,无java文件

    3. 直接运行build.gradle,生成apk文件(注意,运行时Run/Redebug configurations 中Launch Options选择launch nothing),否则build 会报 no default Activty的错误。

    4. 将apk文件重命名,如black.apk重命名为black.skin防止用户点击安装

    相关文章

      网友评论

          本文标题:Android动态皮肤学习总结

          本文链接:https://www.haomeiwen.com/subject/dslkxhtx.html