当前位置: 移动技术网 > 移动技术>移动开发>Android > Android资源管理利器Resources和AssetManager

Android资源管理利器Resources和AssetManager

2019年10月15日  | 移动技术网移动技术  | 我要评论

换肤思路:

1.什么时候换肤?

xml加载前换肤,如果xml加载后换肤,用户将会看见换肤之前的色彩,用户体验不好。

2.皮肤是什么?

皮肤就是apk,是一个资源包,包含了颜色、图片等。

3.什么样的控件应该进行换肤?

包含背景图片的控件,例如textview文字颜色。

4.皮肤与已安装的资源如何匹配?

资源名字匹配

 

效果展示:

 

 

 

 

步骤:

1.xml加载前换肤,意味着需要将所需要换肤的控件收集起来。因此要监听xml加载的过程。

 1 public class baseactivity extends activity {
 2 
 3     skinfactory skinfactory;
 4 
 5     @override
 6     protected void oncreate(@nullable bundle savedinstancestate){
 7         super.oncreate(savedinstancestate);
 8 
 9         //监听xml生成的过程
10         skinfactory = new skinfactory();
11         layoutinflatercompat.setfactory(getlayoutinflater(),skinfactory);
12     }
13 }

 

2.需要换肤的控件收集到一个容器中并且不更改自己的逻辑直接换肤(例如:不用在每个需要换肤的空间里面加上: “ app:...... ”  自定义控件属性)

思考:

(1)安装的apk的id与皮肤id是否一样?

(2)图片的资源、颜色资源都对应r自动生成的id

(3)皮肤包的资源id、r文件的资源id以及app里r文件的资源的id是否是一样的?——是不一样的

 

3.一个activity有多个控件(skinview) 一个控件对应多个换肤属性(skinitem)

skinitem来封装这些值:

  • attrname-属性名(background)
  • attrvalue-属性值id 十六进制(@color/colorprimarydark)
  • attrtype--类型(color)
  • id(r文件的id)
 1 class skinitem{
 2         // attrname   background
 3         string attrname;
 4 
 5         int refid;
 6         // 资源名字  @color/colorprimarydark
 7         string attrvalue;
 8         //  drawable color
 9         string attrtype;
10 
11         public skinitem(string attrname, int refid, string attrvalue, string attrtype) {
12             this.attrname = attrname;
13             this.refid = refid;
14             this.attrvalue = attrvalue;
15             this.attrtype = attrtype;
16         }
17 
18         public string getattrname() {
19             return attrname;
20         }
21 
22         public int getrefid() {
23             return refid;
24         }
25 
26         public string getattrvalue() {
27             return attrvalue;
28         }
29 
30         public string getattrtype() {
31             return attrtype;
32         }
33     }

skinview:

1 class skinview{
2         private view view;
3         private list<skinitem> list;  //收集需要换肤的集合
4 
5         public skinview(view view, list<skinitem> list) {
6             this.view = view;
7             this.list = list;
8         }
9     }

 

收集控件:

skinfactory:

  1 package com.example.apk_demo2;
  2 
  3 import android.content.context;
  4 import android.util.attributeset;
  5 import android.util.log;
  6 import android.view.view;
  7 import android.widget.textview;
  8 
  9 import androidx.core.view.layoutinflaterfactory;
 10 
 11 import java.lang.reflect.constructor;
 12 import java.lang.reflect.invocationtargetexception;
 13 import java.util.arraylist;
 14 import java.util.list;
 15 
 16 // layoutinflaterfactory接口
 17 public class skinfactory implements layoutinflaterfactory {
 18 
 19     private list<skinview> cachelist = new arraylist<>();
 20     private static final string tag = "david" ;
 21     //补充系统控件的包名
 22     private static final string[] prefixlist={"android.widget.","android.view.","android.webkit."};   // 包名,android.webkit为浏览器包,v4、v7包都可以认为是自定义控件
 23 
 24 
 25     /**
 26      * xml生成的时候会回调这个方法,返回值为view
 27      * @param parent
 28      * @param name   控件名
 29      * @param context
 30      * @param attrs
 31      * @return
 32      */
 33     @override
 34     public view oncreateview(view parent, string name, context context, attributeset attrs) {
 35         log.i(tag,"oncreateview:"+name);
 36         // 需要换肤的控件收集到一个容器中
 37 
 38         view view = null;  //初始化view
 39         // 判断自定义与非自定义控件(自定义控件打印时是全报名)
 40         if(name.contains(".")){
 41             // 自定义控件
 42             view = createview(context,attrs,name);  // 获得自定义控件的实例化对象
 43         }else{
 44             // 系统控件
 45             for(string pre : prefixlist){
 46                 view = createview(context,attrs,pre + name);
 47 //                log.i(tag,"创建view:"+view);
 48                 if(view != null){
 49                     // 找对包名,实例化成功
 50                     // 解析view
 51                     //如果不为空则说明实例化成功,找对了包名
 52                     break;
 53                     //找对了可以退出循环
 54                 }
 55             }
 56         }
 57 
 58         if(view != null){
 59             //view不为空则说明已经拿到了这个view,这时候开始解析这个view,判断哪些控件需要换肤
 60             parseskinview(context,attrs,view);
 61             //这个方法用于收集需要换肤的view
 62         }
 63         return view;
 64     }
 65 
 66 
 67     /**
 68      * 收集需要换肤的控件
 69      * @param context
 70      * @param attrs
 71      * @param view
 72      */
 73     private void parseskinview(context context, attributeset attrs, view view) {
 74         list<skinitem> list = new arraylist<>();  //将需要换肤的控件添加到这个集合里面
 75         for(int i = 0; i < attrs.getattributecount(); i++){
 76             //做一个java bean来封装这些值:
 77             // attrname-属性名(background)、attrvalue-属性值id 十六进制(@color/colorprimarydark)、attrtype--类型(color)、id(r文件的id)
 78             // attrname == background等 时 (属性名)
 79             string attrname = attrs.getattributename(i);
 80             // 获得控件的id值,eg:@color/colorprimarydark  (属性值)
 81             string attrvalue = attrs.getattributevalue(i);
 82 
 83             if(attrname.equals("background") || attrname.equals("textcolor")){
 84                 // 需要换肤的控件——具备换肤的潜力,并不是一定需要换肤
 85 //                log.i(tag,"parseskinview:"+attrname);
 86                 int id = integer.parseint(attrvalue.substring(1)); //引用类型
 87 
 88                 string entry_name = context.getresources().getresourceentryname(id);
 89 
 90                 string typenme = context.getresources().getresourcetypename(id);
 91 
 92                 skinitem skinitem = new skinitem(attrname,id,entry_name,typenme);
 93                 list.add(skinitem);
 94             }
 95         }
 96 
 97         if(!list.isempty()){
 98             skinview skinview = new skinview(view,list);
 99             cachelist.add(skinview);
100             //应用换肤  xml加载过程中换肤
101             skinview.apply();
102 
103         }
104     }
105 
106     //点击应用
107     public void apply() {
108         for(skinview skinview : cachelist){
109             skinview.apply();
110         }
111     }
112 
113     public void remove() {
114         for (skinview skinview : cachelist){
115             //清空集合
116 //            cachelist.removeall();
117         }
118     }
119 
120     /**
121      * 一个activity有多个控件
122      * 一个控件对应多个换肤属性
123      */
124     class skinview{
125         private view view;
126         private list<skinitem> list;  //收集需要换肤的集合
127 
128         public skinview(view view, list<skinitem> list) {
129             log.i(tag,"view123:"+view);
130             this.view = view;
131             this.list = list;
132         }
133 
134         //应用换肤
135         public void apply(){
136             //循环需要换肤的skinitem,应用所有的换肤
137             for(skinitem skinitem : list){
138                 log.i(tag,"skinitem:"+skinitem.getattrname());
139                 if("textcolor".equals(skinitem.getattrname())){
140                     log.i(tag,"view_1:"+view);
141                     //if (!skinmanager.getinstance().getskinpackage().equals("")){
142                     //最开始的时候系统没有资源文件,所以当有没有都运行这行代码是,系统没有获得颜色id,因此为灰色。
143                     //所以得加一个判断,在没有换肤之前采用系统默认颜色
144                     if (!skinmanager.getinstance().getskinpackage().equals("")) {
145                         ((textview) view).settextcolor(skinmanager.getinstance().getcolor(skinitem.getrefid()));
146                     }
147                 }
148                 if("background".equals(skinitem.getattrname())){
149                     if("color".equals(skinitem.getattrtype())){
150                         //直接这样设置,没有任何换肤功能,这样加载就是本身默认颜色
151 //                        view.setbackgroundcolor(skinitem.getrefid());
152 
153                         if (!skinmanager.getinstance().getskinpackage().equals("")){
154                             view.setbackgroundcolor(skinmanager.getinstance().getcolor(skinitem.getrefid()));
155                         }
156                     }else if("drawable".equals(skinitem.getattrtype())){
157                         if(!skinmanager.getinstance().getskinpackage().equals("")){
158                             view.setbackgrounddrawable(skinmanager.getinstance().getdrawable(skinitem.getrefid()));
159                         }
160                     }
161 
162                 }
163             }
164         }
165     }
166 
167     /**
168      * 封装值
169      */
170     class skinitem{
171         // attrname   background
172         string attrname;
173         //r里面的id
174         int refid;
175         // 资源名字  @color/colorprimarydark
176         string attrvalue;
177         //  drawable color
178         string attrtype;
179 
180         public skinitem(string attrname, int refid, string attrvalue, string attrtype) {
181             this.attrname = attrname;
182             this.refid = refid;
183             this.attrvalue = attrvalue;
184             this.attrtype = attrtype;
185         }
186 
187         public string getattrname() {
188             return attrname;
189         }
190 
191         public int getrefid() {
192             return refid;
193         }
194 
195         public string getattrvalue() {
196             return attrvalue;
197         }
198 
199         public string getattrtype() {
200             return attrtype;
201         }
202     }
203 
204     /**
205      * 加载自定义控件
206      * @param context
207      * @param attrs
208      * @param name
209      * @return
210      */
211     private view createview(context context, attributeset attrs, string name) {
212         try{
213             //运用反射拿到自定义控件的构造方法,没有性能损耗
214             class viewclazz = context.getclassloader().loadclass(name);
215             constructor<? extends view> constructor = viewclazz.getconstructor(new class[]{context.class,attributeset.class});  //通过反射获得自定义控件的构造方法
216             return constructor.newinstance(context,attrs);  //通过反射而来的构造函数来实例化对象
217         } catch (instantiationexception e) {
218             e.printstacktrace();
219         } catch (invocationtargetexception e) {
220             e.printstacktrace();
221         } catch (nosuchmethodexception e) {
222             e.printstacktrace();
223         } catch (illegalaccessexception e) {
224             e.printstacktrace();
225         } catch (classnotfoundexception e) {
226             e.printstacktrace();
227         }
228 
229         return null;
230     }
231 }

 

 

 

4.收集完毕后,应用换肤 (xml加载过程中换肤)

 

 

创建skinmanager去获得皮肤apk,app通过skinmanager获取皮肤apk

(1)加载皮肤包(loadskin):通过反射获得assermanager的addassetpath()方法,再通过这个方法获得皮肤apk,从而实例化skinresource;再通过packagemanager.getpackagearchiveinfo(path,packagemanager.get_activities).packagename;获得皮肤包名

(2)获取颜色(getcolor):判断skinresource是否为空;拿到res的名字,eg:通过“coloraccent”去寻找id

 

skinmanager:

  1 package com.example.apk_demo2;
  2 
  3 import android.content.context;
  4 import android.content.pm.packagemanager;
  5 import android.content.res.assetmanager;
  6 import android.content.res.resources;
  7 import android.graphics.drawable.drawable;
  8 import android.util.log;
  9 
 10 import androidx.core.content.contextcompat;
 11 
 12 import java.lang.reflect.invocationtargetexception;
 13 import java.lang.reflect.method;
 14 
 15 public class skinmanager {
 16     private static final string tag = "yu" ;
 17     //代表外置卡皮肤app的resource
 18     private resources skinresource;
 19 
 20     private context context;
 21     //皮肤apk包名
 22     private string skinpackage;
 23     // 初始化context
 24     public void init(context context){
 25         // 一定用getapplicationcontext()方法获得context,其是一定存在的;(从内存角度上引用全局上下文)
 26         // 如果是靠参数context,有可能是不存在的(如果activity被销毁了)
 27         this.context = context.getapplicationcontext();
 28     }
 29     private static final skinmanager ourinstance = new skinmanager();
 30 
 31     public static skinmanager getinstance(){ return ourinstance; }
 32 
 33     /**
 34      *加载皮肤包
 35      * @param path 路径
 36      */
 37     public void loadskin(string path){
 38 
 39         // resources(assetmanager assets, displaymetrics metrics, configuration config)
 40         // 实例化assetmanager (@hide)assetmanager()是一个系统保护函数,需要通过反射来调用
 41         try{
 42             assetmanager assetmanager = assetmanager.class.newinstance();
 43             //通过assetmanager.addassetpath(""); 方法获得皮肤apk  需反射
 44             method addassetpath = assetmanager.getclass().getmethod("addassetpath",string.class);
 45             addassetpath.invoke(assetmanager,path);
 46 
 47             skinresource = new resources(assetmanager,context.getresources().getdisplaymetrics(),
 48                     context.getresources().getconfiguration());// 实例化skonresource
 49             // skinresource.getcolor(r.color.coloraccent);通过这样就可以获得资源文件的皮肤设置
 50             packagemanager packagemanager = context.getpackagemanager();  //包管理器
 51             //获得皮肤包名
 52             log.i(tag,"路径"+path);
 53 //            log.i(tag,"上下文"+context);
 54             log.i(tag,"上下文"+context);
 55             skinpackage = packagemanager.getpackagearchiveinfo(path,packagemanager.get_activities).packagename;
 56             log.i(tag,"包名"+skinpackage);
 57         } catch (illegalaccessexception e) {
 58             e.printstacktrace();
 59         } catch (instantiationexception e) {
 60             e.printstacktrace();
 61         } catch (nosuchmethodexception e) {
 62             e.printstacktrace();
 63         } catch (invocationtargetexception e) {
 64             e.printstacktrace();
 65        } catch (exception e){
 66             log.i(tag,"上下文"+context);
 67             log.i(tag,"包名"+skinpackage);
 68         }
 69 
 70     }
 71 
 72     private skinmanager(){ }
 73 
 74     /**
 75      *
 76      * @param resid
 77      * @return
 78      */
 79     public int getcolor(int resid){
 80         //判断有没有皮肤包
 81         if(skinresource == null){
 82             return resid;
 83         }
 84 
 85         //能否通过这个方法获得 int skinid = skinresource.getcolor(resid);
 86         //不能,因为r文件的id与皮肤apk的id不一样
 87         //eg:获得coloraccent
 88         string resname = context.getresources().getresourceentryname(resid);
 89         // public int getidentifier(string name, string deftype, string defpackage)
 90         int skinid = skinresource.getidentifier(resname,"color",skinpackage);
 91         if(skinid == 0){
 92             //如果不合法,返回默认xml
 93             return resid;
 94         }
 95 //        log.i(tag,"resid:"+resid);
 96 //        log.i(tag,"skinresource:"+skinresource.getcolor(skinid));
 97         return skinresource.getcolor(skinid);
 98     }
 99 
100 
101     /**
102      * 判断有无资源可以加载,如没有就用初始化皮肤
103      * @return
104      */
105     public object getskinpackage() {
106         if(skinpackage == null){return "";}
107         return "ok";
108     }
109 
110     public drawable getdrawable(int refid) {
111         if(skinresource == null){
112             return contextcompat.getdrawable(context,refid);
113         }
114         string resname = context.getresources().getresourceentryname(refid);
115         int skinid = skinresource.getidentifier(resname,"drawable",skinpackage);
116         if(skinid == 0){
117             //如果不合法,返回默认xml
118             return contextcompat.getdrawable(context,refid);
119         }
120         return skinresource.getdrawable(refid);
121     }
122 }

 总结:

   从学习android到现在已经过去了一个月,学习最初感觉还好,谁知遇到了换肤这一大难题。

   网上资料非常多,却很难找到一个适合我们的。非常幸运的是,虽然这其中不乏走了很多弯路,但对亏朋友们之间的互相帮助,互相共享学习资料,最后终于做了出来。在自己的项目中也遇到过许许多多的bug需要调试,保持头脑清晰是必须的啦~

   想要跟深入学习的同学,可以去学习github上的开源框架android-skin-loader。这个框架的换肤机制使用动态加载机制前去加载皮肤内容,无需重启即可实时更换。这个框架也可以直接拿来使用,不过个人认为身为一个人程序员还是需要了解好的项目的基本原理的。

  

本章涉及知识,想要了解的朋友可以去我的其他博客android资源管理利器resources和assetmanager 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网