美文网首页
基于ThemeSkinning换肤库的新用法

基于ThemeSkinning换肤库的新用法

作者: 漫步者_d40d | 来源:发表于2020-05-15 11:10 被阅读0次

    Skin换肤库skinlibrary的接入说明

    • 作者:jingzhanwu
    • 2020-05-15

    基于动态加载的换肤库ThemeSkinning项目算是比较完善的了,最近在使用的时候发现我们的Application和Activity以及Fragment需要继承它的SkinBaseApplication、SkinBaseActivity和SkinBaseFragment这三个类,这样一来接入已有项目的时候极为不便,原因是我的Base是基于我的另外一个库MVP来构建的,由此造成的缺点如下。

    • 需要改变原有Base类的继承关系
    • 破坏了原有MVP库的功能单一性
    • 相互依赖关系复杂,扩展差

    通过阅读ThemeSkinning他的源码发现它的基类中只是简单的初始化配置相关代码发现并不复杂,所以就直接下载ThemeSkinning的源码通过依赖skinlibrary库来在自己的项目中进行配置,这样一来就不需要改动我原MVP的代码逻辑了,具体的继承步骤如下。

    一、Skin初始化

    public class App extends Application {
        @Override
        public void onCreate() {
            super.onCreate();
            //skin 初始化
            SkinManager.getInstance().init(this);
            //状态栏颜色可改变
            SkinConfig.setCanChangeStatusColor(true);
            //字体可动态改变
            SkinConfig.setCanChangeFont(true);
            //开启debug模式
            SkinConfig.setDebug(true);
            //添加自定义View的换肤属性,如果没有自定义换肤的view则不用添加
            SkinConfig.addSupportAttr("tabLayoutIndicator", new TabLayoutIndicatorAttr());
            SkinConfig.addSupportAttr("button", new RadioButtonAttr());
            //开启全局换肤
            SkinConfig.enableGlobalSkinApply();
        }
    }
    

    二、Activity配置,可配置在自己的BaseActivity中

    1.实现ISkinUpdate和IDynamicNewView接口

    public class SkinBaseActivity extends AppCompatActivity implements ISkinUpdate, IDynamicNewView {
    

    2.初始化InflaterFactory,必须在onCreate方法中并且在调用super之前

    private SkinInflaterFactory mSkinInflaterFactory;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            mSkinInflaterFactory = new SkinInflaterFactory(this);
            LayoutInflaterCompat.setFactory2(getLayoutInflater(), mSkinInflaterFactory);
            super.onCreate(savedInstanceState);
        }
    
    

    3.在Activity的声明周期函数中添加对应代码,实现ISkinUpdate和IDynamicNewView接口的方法

     @Override
        protected void onResume() {
            super.onResume();
            SkinManager.getInstance().attach(this);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            SkinManager.getInstance().detach(this);
            mSkinInflaterFactory.clean();
        }
    
        @Override
        public void onThemeUpdate() {
            SkinL.i(TAG, "onThemeUpdate");
            mSkinInflaterFactory.applySkin();
            changeStatusColor();
        }
    
        public SkinInflaterFactory getInflaterFactory() {
            return mSkinInflaterFactory;
        }
    
        @Override
        public void dynamicAddView(View view, List<DynamicAttr> pDAttrs) {
            mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, pDAttrs);
        }
    
        @Override
        public void dynamicAddView(View view, String attrName, int attrValueResId) {
            mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, attrName, attrValueResId);
        }
    
        @Override
        public void dynamicAddFontView(TextView textView) {
            mSkinInflaterFactory.dynamicAddFontEnableView(this, textView);
        }
    

    4.如果需要一同改变状态栏颜色,则加入如下代码

    public void changeStatusColor() {
            if (!SkinConfig.isCanChangeStatusColor()) {
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                int color = SkinResourcesUtils.getColorPrimaryDark();
                if (color != -1) {
                    Window window = getWindow();
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    window.setStatusBarColor(SkinResourcesUtils.getColorPrimaryDark());
                }
            }
        }
    

    5.完整代码如下

    public class SkinBaseActivity extends AppCompatActivity implements ISkinUpdate, IDynamicNewView {
        private final static String TAG = "SkinBaseActivity";
    
        private SkinInflaterFactory mSkinInflaterFactory;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            mSkinInflaterFactory = new SkinInflaterFactory(this);
            LayoutInflaterCompat.setFactory2(getLayoutInflater(), mSkinInflaterFactory);
            super.onCreate(savedInstanceState);
            changeStatusColor();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            SkinManager.getInstance().attach(this);
        }
    
        @Override
        protected void onDestroy() {
            super.onDestroy();
            SkinManager.getInstance().detach(this);
            mSkinInflaterFactory.clean();
        }
    
        @Override
        public void onThemeUpdate() {
            SkinL.i(TAG, "onThemeUpdate");
            mSkinInflaterFactory.applySkin();
            changeStatusColor();
        }
    
        public SkinInflaterFactory getInflaterFactory() {
            return mSkinInflaterFactory;
        }
    
        @Override
        public void dynamicAddView(View view, List<DynamicAttr> pDAttrs) {
            mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, pDAttrs);
        }
    
        @Override
        public void dynamicAddView(View view, String attrName, int attrValueResId) {
            mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, attrName, attrValueResId);
        }
    
        @Override
        public void dynamicAddFontView(TextView textView) {
            mSkinInflaterFactory.dynamicAddFontEnableView(this, textView);
        }
    
        public void changeStatusColor() {
            if (!SkinConfig.isCanChangeStatusColor()) {
                return;
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                int color = SkinResourcesUtils.getColorPrimaryDark();
                if (color != -1) {
                    Window window = getWindow();
                    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                    window.setStatusBarColor(SkinResourcesUtils.getColorPrimaryDark());
                }
            }
        }
    }
    

    三、Fragment配置,可配置在自己的BaseFragment中

    public class SkinBaseFragment extends Fragment implements IDynamicNewView {
    
        private IDynamicNewView mIDynamicNewView;
    
        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
            try {
                mIDynamicNewView = (IDynamicNewView) context;
            } catch (ClassCastException e) {
                mIDynamicNewView = null;
            }
        }
    
        @Override
        public final void dynamicAddView(View view, List<DynamicAttr> pDAttrs) {
            if (mIDynamicNewView == null) {
                throw new RuntimeException("IDynamicNewView should be implements !");
            } else {
                mIDynamicNewView.dynamicAddView(view, pDAttrs);
            }
        }
    
        @Override
        public final void dynamicAddView(View view, String attrName, int attrValueResId) {
            mIDynamicNewView.dynamicAddView(view, attrName, attrValueResId);
        }
    
        @Override
        public final void dynamicAddFontView(TextView textView) {
            mIDynamicNewView.dynamicAddFontView(textView);
        }
    
        public final SkinInflaterFactory getSkinInflaterFactory() {
            if (getActivity() instanceof SkinBaseActivity) {
                return ((SkinBaseActivity) getActivity()).getInflaterFactory();
            }
            return null;
        }
    
        @Override
        public void onDestroyView() {
            removeAllView(getView());
            super.onDestroyView();
        }
    
        protected void removeAllView(View v) {
            if (v instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) v;
                for (int i = 0; i < viewGroup.getChildCount(); i++) {
                    removeAllView(viewGroup.getChildAt(i));
                }
                removeViewInSkinInflaterFactory(v);
            } else {
                removeViewInSkinInflaterFactory(v);
            }
        }
    
        private void removeViewInSkinInflaterFactory(View v) {
            if (getSkinInflaterFactory() != null) {
                //此方法用于Activity中Fragment销毁的时候,移除Fragment中的View
                getSkinInflaterFactory().removeSkinView(v);
            }
        }
    }
    

    四、xml布局文件的修改

    在所有需要动态换肤的布局文件加入skin的命名空间,并配置属性:skin:enable="true"

    xmlns:skin="http://schemas.android.com/android/skin"
    skin:enable="true"
     <?xml version="1.0" encoding="utf-8"?>
     <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
         xmlns:skin="http://schemas.android.com/android/skin"
         xmlns:tools="http://schemas.android.com/tools"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:background="@drawable/selector_item"
         android:gravity="center_horizontal"
         android:orientation="vertical"
         android:padding="10dp"
         skin:enable="true"
         tools:ignore="MissingPrefix">
         <ImageView
             android:id="@+id/iv_img"
             android:layout_width="80dp"
             android:layout_height="80dp"
             android:src="@mipmap/mipmap_img"
             skin:enable="true"
             tools:ignore="ContentDescription" />
         <TextView
             android:id="@+id/tv_title"
             style="@style/ItemTitleText"
             android:layout_marginTop="5dp"
             android:padding="10dp"
             android:text="style attr"
             skin:enable="true"
             tools:ignore="HardcodedText" />
         <TextView
             android:id="@+id/tv_content"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
             android:layout_marginTop="5dp"
             android:text="normal attr"
             android:textColor="@color/item_tv_content_color"
             android:textSize="16sp"
             skin:enable="true"
             tools:ignore="HardcodedText" />
         </LinearLayout>
     
     </LinearLayout>
    

    五、配置换肤资源包

    将自己的资源module 打包成后缀为 .skin的文件放入自己项目app module下的 /assets/skin目录下;如果有有字体的话放入 /assets/fonts目录下.

    六、开始换肤

    1.系统view换肤

    通过调用SkinManager的loadSkin方法来进行动态换肤

     SkinManager.getInstance().loadSkin("theme-20171126.skin",
                            new SkinLoaderListener() {
                                @Override
                                public void onStart() {
                                    Log.i("SkinLoaderListener", "正在切换中");
                                    //dialog.show();
                                }
    
                                @Override
                                public void onSuccess() {
                                    Log.i("SkinLoaderListener", "切换成功");
                                }
    
                                @Override
                                public void onFailed(String errMsg) {
                                    Log.i("SkinLoaderListener", "切换失败:" + errMsg);
                                }
    
                                @Override
                                public void onProgress(int progress) {
                                    Log.i("SkinLoaderListener", "皮肤文件下载中:" + progress);
    
                                }
                            }
    
                    );
    

    2.自定义view换肤

    (1).自定义view的换肤属性定义

    继承SkinAttr 类,实现applySkin(View view)方法,设置需要换肤的属性值,如下列举了TabLayout的tabLayoutIndicator属性改变颜色与RadioButton改变button属性的例子

    public class TabLayoutIndicatorAttr extends SkinAttr {
    
        @Override
        protected void applySkin(View view) {
            if (view instanceof TabLayout) {
                TabLayout tl = (TabLayout) view;
                if (isColor()) {
                    int color = SkinResourcesUtils.getColor(attrValueRefId);
                    tl.setSelectedTabIndicatorColor(color);
                }
            }
        }
    }
    
    public class RadioButtonAttr extends SkinAttr {
        @Override
        protected void applySkin(View view) {
            if (view instanceof RadioButton) {
                if (isDrawable()) {
                    RadioButton radioButton = (RadioButton) view;
                    Drawable drawable = SkinResourcesUtils.getDrawable(attrValueRefId);
                    radioButton.setButtonDrawable(drawable);
                }
    
            }
        }
    }
    
    (2).在Application初始化skin的时候添加要动态换肤的自定义view的属性
      //添加自定义View的换肤属性
            SkinConfig.addSupportAttr("tabLayoutIndicator", new TabLayoutIndicatorAttr());
            SkinConfig.addSupportAttr("button", new RadioButtonAttr());
    
    (3).Activity或者Fragment中调用

    调用dynamicAddView方法添加需要换肤的view的属性和对应的属性值

     private void setUpView() {
            Toolbar toolbar = findViewById(R.id.toolbar);
            toolbar.setTitle("我是Toolbar");
            setSupportActionBar(toolbar);
            dynamicAddView(toolbar, "background", R.color.colorPrimaryDark);
    
            TabLayout tablayout = findViewById(R.id.tablayout);
            for (int i = 0; i < DataProvider.getTitleList().size(); i++) {
                tablayout.addTab(tablayout.newTab().setText(DataProvider.getTitleList().get(i)));
            }
            dynamicAddView(tablayout, "tabLayoutIndicator", R.color.colorPrimaryDark);
    
        }
    

    skinlibrary库来源于开源项目ThemeSkinning,感谢ThemeSkinning库的作者

    相关文章

      网友评论

          本文标题:基于ThemeSkinning换肤库的新用法

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