文章标题

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();

以上讲得都是基本原理,接下来有时间会谈一谈这俩个的架构区别

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值