文章标题
2015-09-28 20:35
351 查看
android 主题切换的实现
1.自定义view,给控件加上 setTheme方法
2. 初始化绑定 view和view要设置的属性,然后通过分开每个单独setter设置实际属性
原理相同:都是给自定义属性– 放到主题Theme里,然后通过原有属性引用到它。多个theme来给这些Theme的属性赋值,代码中拿到Theme这个属性值并设置进去。
看完上面的原理,我们还是有许多疑惑:
Theme是什么,系统调用setTheme究竟改变了什么?
属性的含义是什么,属性所对应的value是如何拿到的?
android资源的获取,我们常常关注一个textView的背景颜色资源的获得,然而那些属性是
怎样定义的,像我们声明类型一样,这是在哪定义的呢。
其实这些资源属性都交给attr去定义:
我们常常在res/values/zzz.xml
在这里声明里叫做WindowBackground的,其中类型为引用的。
于是对应的当系统解析xml时,会将这些控件属性以及值给该控件如
”’
public ColorButton(Context context, AttributeSet attrs) {}
”’
即构造方法里传入的AttributeSet,
一个关于组件的集合,关联到xml的每个tag
通常我们不会直接使用这个接口,Theme.obtainStyledAttributes()会小心将这些属性转换好。
确切地说,Resouces Api会将资源引用(属性的值如 “@string/my_label”)转换为相应的具体类型给你。如果直接使用AttributeSet,你需要检查资源的引用getAttributeResouceValue(int,int),然后访问自己的资源。
当使用属性使用style或者them时,直接使用AttributeSet拿到属性值也会非常不方便。
我们将这些attr组合到styleabled里使用
public TypedArray obtainAttributes (AttributeSet set, int[] attrs)
从AttributeSet查询获得一组基本属性值放入到TypedArray保存
将attr组织归类,使得控件根据它组织获取,这就是为什么系统控件只能有那些属性的原因。
Theme属性指向一个style,一般这些style能包含的属性是能被识别的,就是名称为Theme的styleable。
style是什么呢?
属性的名称集合,将属性的赋值从中单个转移出来,从而达到复用。如果程序读取xml文件时发现是一个style,则会从style指向的id处重新找到该style所包含的属性值。
public static int getAttributeValue(AttributeSet attr, int paramInt) { int value = -1; int count = attr.getAttributeCount(); for(int i = 0; i <count;i++) { if(attr.getAttributeNameResource(i) == paramInt) { String str = attr.getAttributeValue(i); if(null != str && str.startsWith("?")) { value = Integer.valueOf(str.substring(1,str.length())).intValue(); return value; } } } return value; }
TypedArray ta = theme.obtainStyledAttributes(new int[]{paramInt}); Drawable drawable = ta.getDrawable(0); ta.recycle();
TypedArray a = newTheme.obtainStyledAttributes(themeId, new int[] { mAttrResId }); int attributeResourceId = a.getResourceId(0, 0); Drawable drawable = mView.getResources().getDrawable( attributeResourceId); a.recycle();
以上讲得都是基本原理,接下来有时间会谈一谈这俩个的架构区别
相关文章推荐
- parted
- proc
- 闭包结构(多层)
- JS浮点运算错误的解决
- 基础数据结构--栈实现
- 解决Eclipse建立Maven项目后无法建立src/main/java资源文件夹的办法
- 【Unity技巧】四元数(Quaternion)和旋转
- noip2013
- C语言-文件操作函数(部分)
- 通知 ------- Notification
- hdu5942
- 大数据和云计算的区别是什么?
- lightoj(基础数学)
- 编译原理:第七节 及词法分析器的C++和Python实现
- Evaluate Reverse Polish Notation(堆栈)
- cocos代码研究(2)Layer学习笔记
- net-snmp配置文件详解
- Linux学习笔记——系统启动流程
- [APUE]再读之高级IO
- iOS大典之动态相册