Android主题更换换肤

知识总览

android主题换肤通常借助LayoutInflater#setFactory实现换肤。

换肤步骤:

  1. 通过解析外部的apk压缩文件,创建自定义的Resource对象去访问apk压缩文件的资源。
  2. 借助LayoutInfater#setFactoy,将步骤(1)中的资源应用到View的创建过程当中。

认识setFactory

平常设置或者获取一个View时,用的较多的是setContentViewLayoutInflater#inflatesetContentView内部也是通过调用LayoutInflater#inflate实现(具体调用在AppCompatViewInflater#setContentView(ind resId)中)。

通过LayoutInflater#inflate可以将xml布局文件解析为所需要的View,通过分析LayoutInflate#inflate源码,可以看到.xml布局文件在解析的过程中会调用LayoutInflater#rInflate,随后会通过调用LayoutInflater#createViewFromTag来创建View。这里推荐《遇见LayoutInflater&Factory
下面一起看看View的创建过程LayoutInflate#createViewFormTag:

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
   
        if (name.equals("view")) {
   
            name = attrs.getAttributeValue(null, "class");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        if (!ignoreThemeAttr) {
   
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
   
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        if (name.equals(TAG_1995)) {
   
            // Let's party like it's 1995!
            return new BlinkLayout(context, attrs);
        }

        try {
   
            View view;
            if (mFactory2 != null) {
   
            	//根据attrs信息,通过mFactory2创建View
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
   
            	//根据attrs信息,通过mFactory创建View
                view = mFactory.onCreateView(name, context, attrs);
            } else {
   
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
   
                view = mPrivateFactory.onCreateView(parent, name, context, attrs
  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值