2 Star 7 Fork 1

刘铭宇 / PaintedSkin

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

PaintedSkin

    一款解决Android App 换肤框架,极低的侵入性与学习成本。

Gitter build Hex.pm


最新版本

模块 说明 版本
PaintedSkin 换肤核心包
StandardPlugin 减少代码侵入的插件包
AutoPlugin 全自动插件包
ConstraintLayoutCompat ConstraintLayout换肤兼容包
TypefacePlugin 替换字体插件

版本履历

V3.0.0
  • 支持AndroidX.
V3.0.1
  • 修复无法初始化默认皮肤包问题.
V3.0.2
  • 剥离对于Reflex库的依赖.
V3.0.3
  • 减少无意义日志输出、优化对于ColorStateList的加载.
V3.1.0
  • 剥离依赖,上传至公网Maven
V3.1.1
  • 优化动态添加换肤View设置资源时机
V3.1.2
  • 修复由于onThemeSkinSwitch函数内部逻辑错误导致换肤失败问题
V3.1.5
  • JCenter移植至Jitpack
V3.1.6
  • 移除冗余Log
V3.1.7
  • 修复由于缓存Drawable与ColorStateList导致得后加载资源状态异常问题
V3.1.8
  • 修复由于Android Q及更高版本中限制非SDK接口访问导致的初始化崩溃问题
  • 适配Android Q及更高版本文件目录分区访问
V3.2.0
  • ISwitchThemeSkinObserver增加onThemeSkinSwitchRunOnUiThread 接口

框架实现原理


功能介绍

  1. 支持XML全部View换肤
  2. 支持XML指定View换肤
  3. 支持代码创建View换肤
  4. 支持自定义View、三方库提供的View、自定义属性换肤
  5. 支持绝大部分基础View换肤
  6. 支持差异化换肤(适用于部分View节日换肤)
  7. [支持全局动态替换字体](#TypefacePlugin 使用)
  8. 支持通过拦截器拦截View创建过程
  9. 支持Androidx、support
  10. 支持定制扩展
  11. 不会与其他依赖LayoutInflater.Factory 的库冲突

使用

添加依赖

  1. 在工程的build.gradle文件中添加:

buildscript {
    repositories {
		maven { url "https://jitpack.io" } // 必须添加
    }
    dependencies {
        ...
        classpath 'com.hujiang.aspectjx:gradle-android-plugin-aspectjx:2.0.10' // 如果不使用AutoPlugin可以不添加
    }
    allprojects {
		maven { url "https://jitpack.io" } // 必须添加
    }
}
  1. 如需使用AutoPlugin,在项目appbuild.gradle文件中添加:

apply plugin: 'android-aspectjx' 
android {
	...
}
  1. 在项目appbuild.gradle文件中添加::

dependencies {
	// 依赖的反射库
 	implementation 'com.github.CoderAlee:Reflex:1.2.0'
 	// 核心库
    implementation 'com.github.CoderAlee.PaintedSkin:PaintedSkin:TAG'
	implementation 'com.github.CoderAlee.PaintedSkin:StandardPlugin:TAG'
	// StandardPlugin 与 AutoPlugin 只需添加一个
	annotationProcessor 'com.github.CoderAlee.PaintedSkin:AopPlugin:TAG'
	implementation 'com.github.CoderAlee.PaintedSkin:AopPlugin:TAG'
	//如果项目中的ConstraintLayout需要换肤则引入
	implementation 'com.github.CoderAlee.PaintedSkin:ConstraintLayoutCompat:TAG'
	// 需要替换字体库时引入
	implementation 'com.github.CoderAlee.PaintedSkin:TypefacePlugin:TAG'
    ...
}

运行配置

PaintedSkin支持三种换肤模式:

SkinMode.REPLACE_ALL 所有View都参与换肤,添加了skin:enable="false" 标签的View 将不参与换肤;

SkinMode.REPLACE_MARKED 只有添加了**skin:enable="true"**标签的View才参与换肤;

SkinMode.DO_NOT_REPLACE 任何View都不参与换肤

API:

public final class App extends Application {
    static {
        Config.getInstance().setSkinMode(Config.SkinMode.REPLACE_ALL);
    }
}

PaintedSkin 支持调试模式与严格模式:

调试模式下将输出框架内的一些关键节点Log以及换肤任务执行耗时时长;

严格模式下如果框架内出现错误将直接抛出异常;

API:

public final class App extends Application {
    static {
         Config.getInstance().setEnableDebugMode(false);
         Config.getInstance().setEnableStrictMode(false);
    }
}

插件使用

StandardPlugin 使用:

public final class App extends Application {
    
    @Override
    public void onCreate() {
        super.onCreate();
        WindowManager.getInstance().init(this,new OptionFactory());
    }
}
final class OptionFactory implements IOptionFactory {
    @Override
    public int defaultTheme() {
        return 0;
    }

    @Override
    public IThemeSkinOption requireOption(int theme) {
        switch (theme) {
            case 1:
                return new NightOption();
            default:
                return null;
        }
    }
}

AutoPlugin 不再需要开发人员调用初始化代码,只需要在实现了IOptionFactory 接口的实现类上添加注解**@Skin** 即可:

@Skin
public final class OptionFactory implements IOptionFactory {
    @Override
    public int defaultTheme() {
        return 0;
    }

    @Override
    public IThemeSkinOption requireOption(int theme) {
        switch (theme) {
            case 1:
                return new NightOption();
            default:
                return null;
        }
    }
}

主题配置

class NightOption implements IThemeSkinOption {

    @Override
    public LinkedHashSet<String> getStandardSkinPackPath() {
        LinkedHashSet<String> pathSet = new LinkedHashSet<>();
        pathSet.add("/sdcard/night.skin");
        return pathSet;
    }
}

换肤

 ThemeSkinService.getInstance().switchThemeSkin(int theme);

皮肤包构建

  1. 新建Android application工程

  2. 皮肤工程包名不能和宿主应用包名相同

  3. 将需要换肤的资源放置于res对应目录下

    例如 Button 文字颜色

    APK 中res/values/colors.xml

    <color name="textColor">#FFFFFFFF</color>

    皮肤包中 res/values/colors.xml

    <color name="textColor">#FF000000</color>

    例如 Button 背景图片

    APK 中 res/mipmap/bg_button.png

    皮肤包中 res/mipmap/bg_button.png

  4. 在皮肤包工程的build.gradle文件中添加:

      applicationVariants.all { variant ->
            variant.outputs.all { output ->
                outputFileName = "xxx.skin"
            }
        }

动态创建View换肤

核心接口WindowManager.getInstance().getWindowProxy(getContext()).addEnabledThemeSkinView(View,SkinElement);

  TextView textView = new TextView(getContext());
        textView.setTextColor(getResources().getColor(R.color.textColor));
        textView.setText("动态创建View参与换肤");
        WindowManager.getInstance().getWindowProxy(getContext()).addEnabledThemeSkinView(textView, new SkinElement("textColor", R.color.textColor));
        layout.addView(textView);

进阶用法

拦截View创建过程

        ThemeSkinService.getInstance().getCreateViewInterceptor().add(new LayoutInflater.Factory2() {
            @Nullable
            @Override
            public View onCreateView(@Nullable View parent, @NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
                return onCreateView(name, context, attrs);
            }

            @Nullable
            @Override
            public View onCreateView(@NonNull String name, @NonNull Context context, @NonNull AttributeSet attrs) {
                if (TextUtils.equals(name,"TextView")){
                    return new Button(context, attrs);
                }
                return null;
            }
        });

通过拦截View的创建过程其实可以实现很多骚操作,比如上面这段代码就可以将全局的TextView替换成Button。这比在XML中一个一个修改要快捷方便的多。其中Google 就是通过这种方式将Button 替换为AppCompatButton。AppCompatDelegate也是同样的技术方案。

自定义View、三方库View换肤

当自定义View或使用的三方库View中有自定义属性需要换肤时:

  1. 实现IThemeSkinExecutorBuilder 接口,用于解析支持换肤属性并创建对应属性的换肤执行器。可以参考框架内自带的DefaultExecutorBuilder:

    @RestrictTo(RestrictTo.Scope.LIBRARY)
    public final class DefaultExecutorBuilder implements IThemeSkinExecutorBuilder {
        /**
         * 换肤支持的属性 背景
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_BACKGROUND = "background";
        /**
         * 换肤支持的属性 前景色
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_FOREGROUND = "foreground";
        /**
         * 换肤支持的属性 字体颜色
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_TEXT_COLOR = "textColor";
        /**
         * 换肤支持的属性 暗示字体颜色
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_TEXT_COLOR_HINT = "textColorHint";
        /**
         * 换肤支持的属性 选中时高亮背景颜色
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_TEXT_COLOR_HIGH_LIGHT = "textColorHighlight";
        /**
         * 换肤支持的属性 链接的颜色
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_TEXT_COLOR_LINK = "textColorLink";
        /**
         * 换肤支持的属性 进度条背景
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_PROGRESS_DRAWABLE = "progressDrawable";
        /**
         * 换肤支持的属性 ListView分割线
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_LIST_VIEW_DIVIDER = "divider";
        /**
         * 换肤支持的属性 填充内容
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_SRC = "src";
        /**
         * 换肤支持的属性 按钮背景
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public static final String ATTRIBUTE_BUTTON = "button";
        private static final Map<Integer, String> SUPPORT_ATTR = new HashMap<>();
    
        static {
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_background, ATTRIBUTE_BACKGROUND);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_foreground, ATTRIBUTE_FOREGROUND);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_textColor, ATTRIBUTE_TEXT_COLOR);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_textColorHint, ATTRIBUTE_TEXT_COLOR_HINT);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_textColorHighlight, ATTRIBUTE_TEXT_COLOR_HIGH_LIGHT);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_textColorLink, ATTRIBUTE_TEXT_COLOR_LINK);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_progressDrawable, ATTRIBUTE_PROGRESS_DRAWABLE);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_divider, ATTRIBUTE_LIST_VIEW_DIVIDER);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_src, ATTRIBUTE_SRC);
            SUPPORT_ATTR.put(R.styleable.BasicSupportAttr_android_button, ATTRIBUTE_BUTTON);
        }
    
        /**
         * 解析支持换肤的属性
         *
         * @param context      {@link Context}
         * @param attributeSet {@link AttributeSet}
         * @return {@link SkinElement}
         */
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        @Override
        public Set<SkinElement> parse(@NonNull Context context, @NonNull AttributeSet attributeSet) {
            TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.BasicSupportAttr);
            if (null == typedArray) {
                return null;
            }
            Set<SkinElement> elementSet = new HashSet<>();
            try {
                for (Integer key : SUPPORT_ATTR.keySet()) {
                    try {
                        if (typedArray.hasValue(key)) {
                            elementSet.add(new SkinElement(SUPPORT_ATTR.get(key), typedArray.getResourceId(key, -1)));
                        }
                    } catch (Throwable ignored) {
                    }
                }
            } catch (Throwable ignored) {
            } finally {
                typedArray.recycle();
            }
            return elementSet;
        }
    
        /**
         * 需要换肤执行器
         *
         * @param view    需要换肤的View
         * @param element 需要执行的元素
         * @return {@link ISkinExecutor}
         */
        @Override
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public ISkinExecutor requireSkinExecutor(@NonNull View view, @NonNull SkinElement element) {
            return BasicViewSkinExecutorFactory.requireSkinExecutor(view, element);
        }
    
        /**
         * 是否支持属性
         *
         * @param view     View
         * @param attrName 属性名称
         * @return true: 支持
         */
        @Override
        @RestrictTo(RestrictTo.Scope.LIBRARY)
        public boolean isSupportAttr(@NonNull View view, @NonNull String attrName) {
            return SUPPORT_ATTR.containsValue(attrName);
        }
    }
    1. 继承BaseSkinExecutor 提供对应属性的换肤执行器:

      public class ViewSkinExecutor<T extends View> extends BaseSkinExecutor<T> {
      
          public ViewSkinExecutor(@NonNull SkinElement fullElement) {
              super(fullElement);
          }
      
          @Override
          protected void applyColor(@NonNull T view, @NonNull ColorStateList colorStateList, @NonNull String attrName) {
              switch (attrName) {
                  case ATTRIBUTE_BACKGROUND:
                  case ATTRIBUTE_FOREGROUND:
                      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                          applyDrawable(view, new ColorStateListDrawable(colorStateList), attrName);
                      } else {
                          applyColor(view, colorStateList.getDefaultColor(), attrName);
                      }
                      break;
                  default:
                      break;
              }
          }
      
          @Override
          protected void applyColor(@NonNull T view, int color, @NonNull String attrName) {
              switch (attrName) {
                  case ATTRIBUTE_BACKGROUND:
                      view.setBackgroundColor(color);
                      break;
                  case ATTRIBUTE_FOREGROUND:
                      applyDrawable(view, new ColorDrawable(color), attrName);
                      break;
                  default:
                      break;
              }
          }
      
      
          @Override
          protected void applyDrawable(@NonNull T view, @NonNull Drawable drawable, @NonNull String attrName) {
              switch (attrName) {
                  case ATTRIBUTE_BACKGROUND:
                      view.setBackground(drawable);
                      break;
                  case ATTRIBUTE_FOREGROUND:
                      view.setForeground(drawable);
                      break;
                  default:
                      break;
              }
          }
      }
      
  2. 将自定义的ThemeSkinExecutorBuilder添加到框架中:

     ThemeSkinService.getInstance().addThemeSkinExecutorBuilder(xxx);

ConstraintLayout换肤兼容包使用

public final class App extends Application {
    static {
        ConstraintLayoutCompat.init();
    }
}

TypefacePlugin 使用

public final class App extends Application {
    static {
        TypefacePlugin.init();
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
       TypefacePlugin.getInstance().setEnable(true).switchTypeface(Typeface);
    }
}

License Apache-2.0

Copyright [2018] [MingYu.Liu]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

一款解决Android App 换肤框架,极低的侵入性与学习成本。 展开 收起
Android
Apache-2.0
取消

发行版 (3)

全部

贡献者

全部

近期动态

加载更多
不能加载更多了
Android
1
https://gitee.com/MingYu-Liu/Painted-Skin.git
git@gitee.com:MingYu-Liu/Painted-Skin.git
MingYu-Liu
Painted-Skin
PaintedSkin
master

搜索帮助