LayoutInflater 源码解析

LayoutInflater 在开发中是经常使用的一个类,一般我们都通过 from 方法获取 LayoutInflater 的实例,并通过其 inflate 方法解析 xml 文件。这么常用与重要的类值得我们去追着源码更深程度的去理解 xml 文件的加载和解析过程。

一、LayoutInflater 构造过程

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

关于 LayoutInlnflater 的 from 方法,我们可以通过 这篇博客 看一下,讲了通过 Context 构建 LayoutInflater 的过程。

这篇博客中提到了 LayoutInflater 的 from 方法最后返回的是一个 PhoneLayoutInflater 类的对象,该类继承了 LayoutInflater 并实现了其抽象方法

接着我们来分析 LayoutInflater 的 inflate 方法的工作过程

二、LayoutInflater 的 inflate 方法的工作过程

// LayoutInflater
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
    final Resources res = getContext().getResources();
    if (DEBUG) {
        Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                + Integer.toHexString(resource) + ")");
    }

    // 由 Resources 构建布局的解析器
    final XmlResourceParser parser = res.getLayout(resource);
    try {
        // 解析布局文件,并将结果返回
        return inflate(parser, root, attachToRoot);
    } finally {
        parser.close();
    }
}

// LayoutInflater
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
    synchronized (mConstructorArgs) {
    
        final Context inflaterContext = mContext; // 存储 Context
        final AttributeSet attrs = Xml.asAttributeSet(parser);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = inflaterContext;
        
        // 1. 将返回结果设置为 父 View
        View result = root;

        try {
            // 2. 寻找根布局
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG &&
                    type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }

            // 2.1 如果没有找到根布局的开始节点,抛出异常
            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription()
                        + ": No start tag found!");
            }
            
            // 3. 得到布局起始节点名字
            final String name = parser.getName(); 
    
            ...
            
            if (TAG_MERGE.equals(name)) { // 3.1 处理节点是 Merge 的情况
                if (root == null || !attachToRoot) {
                    throw new InflateException("<merge /> can be used only with a valid "
                            + "ViewGroup root and attachToRoot=true");
                }

                rInflate(parser, root, inflaterContext, attrs, false);
            } else {
                
                // 3.2 临时根布局找到,根据名字构建 View
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                // 4. 声明 LayoutParams
                ViewGroup.LayoutParams params = null;

                if (root != null) {
                  
                    // 4.1 父 View 不为空时根据 父 View 构建布局的 LayoutParams
                    params = root.generateLayoutParams(attrs);
                    if (!attachToRoot) {
                        // 4.1.1 为 View 设置 LayoutParams
                        temp.setLayoutParams(params);
                    }
                }

                
                // 5. 布局该 View 下所有的子 View
                rInflateChildren(parser, temp, attrs, true);

                // 6.1 如果 父View 不为空并且设置为添加,则将布局的 View 对象添加到父 View
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }

                // 6.2 如果 父 View 为空,则直接返回布局的 View 对象
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }

        }... // 省略 catch
        
        // 7. 返回
        return result;
    }
}
    
  1. 接下来说的 父 View 指的是 inflate 方法的第二个参数。根 View 说的是要解析的布局文件的根 View,注意不要混淆

  2. 将方法返回值设置为 父 View

  3. 寻找布局的根 View 的起始节点,如果找不到,抛出异常,如果找到则继续

  4. 判断根 View 的起始节点,如果是 Merge ,则解析 Merge 下的子 View 并将其 View 添加到 父 View 中。如果不是 Merge,则根据根 View 的名字构建根 View 对象

  5. 有根 View 对象以后,再解析其内部的子 View,调用 rInflateChildren 方法,将根View 的子 View 都添加到根 View 中

  6. 创建布局根 View 的 LayoutParams,如果 父 View 不为空,则根据根 View 在 xml 中声明的属性构建 LayoutParams,并为 根 View 设置该 LayoutParams,如果没有父 View 则不位根 View 添加 LayoutParams

  7. 如果父 View 为空,则将返回值设置为根 View

  8. 返回结果

接下来我们逐个分析,先看创建 View 的方法

一、createViewFromTag 方法工作过程

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

        ...

        try {
            View view;
            
            ... // 1. 用户可以通过设置 LayoutInflater 的 Factory 来创建 View, 默认 Factory 都为空,忽略
            
             // 2. 没有 Factory的请求,通过 onCreateView 或者 createView 创建
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) { // 3. View 名字中没有 . 符号,说明是系统提供的 View
                        view = onCreateView(parent, name, attrs); // 3.1 内置 View 的解析
                    } else { // 4. View 的名字中有 . 符号,说明是自定义 View
                        view = createView(name, null, attrs); // 4.1 自定义 View 的解析
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            
            // 返回 View
            return view;
        } catch...
    }

主要步骤如下:

  1. 根据 Factory 创建 View,默认忽略

  2. 判断是系统 View 还是自定义 View,这里的判断方法是依据系统 View 在布局中不需要添加包名,而自定义 View 必须加包名

  3. 系统 View 则调用 onCreateView 方法,熟悉吗,这个不就是 Activity 的 onCreate 方法中调用的 onCreateView 方法吗,确实是的

  4. 自定义 View 则调用 createView 方法

// PhoneLayoutInflater
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
    for (String prefix : sClassPrefixList) {
        try {
            View view = createView(name, prefix, attrs);
            if (view != null) {
                return view;
            }
        } ...
    return super.onCreateView(name, attrs);
}

onCreateView 方法中会先为 View 的 name 添加系统 View 的前缀来构建完整包名之后再调用 createView 方法创建 View , 也就是说不管是系统 View 还是自定义 View 最后都调用 createView 方法创建

二、createView 方法的工作过程

    // LayoutInflater
    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
            
        // 1. 从缓存中获取构造方法 
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
                // 2. 如果缓存中没有构造方法,则通过反射构造该类
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                
                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                
                // 3. 通过 Class 获取构造方法, 并添加到缓存
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
               ... 缓存中获取到构造方法的情况,省略
            }

            Object[] args = mConstructorArgs;
            args[1] = attrs;
            
            // 4. 由构造方法再通过反射机制构造该 View 类的对象,并返回
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;

        } catch ...
    }
    

createView 的工作过程主要就是根据 View 类的完整路径构造该类的对象并返回。这就是单个 View 的构造过程。如果我们的窗口是一棵视图树,LayoutInflater 需要解析完这棵树,这个任务就交给了 rInflateChildren 方法

三、rInflateChildren 方法工作过程

rInflateChildren 方法会直接调用 reInflate 方法

    // LayoutInflater
    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth(); // 获取当前视图深度
        int type;
        
        // 挨个解析视图树
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }
            
            final String name = parser.getName();
            
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) { // 遇到 include 标签时
                if (parser.getDepth() == 0) { // 如果当前视图深度是 0 并且是 include 标签则抛出异常,因为 include 不能使根 View
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) { // 如果遇到 Merge 则抛出异常,因为 Merge 必须是根标签
                throw new InflateException("<merge /> must be the root element");
            } else {
                // 解析普通 View 标签
                final View view = createViewFromTag(parent, name, context, attrs); // 构建 View
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs); // 根据 Parent 构建 LayoutParams
                rInflateChildren(parser, view, attrs, true); // 递归调用进行解析
                viewGroup.addView(view, params); // 将解析到的 View 添加到它的 parent 中
            }
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

rInflate 的工作过程主要是依次解析视图树中的子 View ,并递归调用解析子 View 中的元素,并将解析到的 View 回溯回来将其添加到 父 View 中

这样 inflate 方法的返回结果就是包含整个布局的 View 对象

注意,这里其实有一个问题,那就是我们在使用 Fragment 和 AbsListView 的时候,如果我们在创建 View 的时候,使用了 LayoutInflater ,我们一定不可以将 inflate 的第二个参数设置为父 View ,或者说如果设置第二个参数那么第三个参数一定要设置为 false。如果设置第二个参数且第三个参数为 true,那么返回的结果就是已经添加了我们需要的 View 的父 View ,我们再返回时这两个类还回把我们返回的父 View 再添加到原来的 父 View,就会抛出异常

四、LayoutInflater 的 inflate 方法工作过程总结

  1. 构建解析器,由解析器获取根 View 的 name
  2. 由根 View 的 name 调用 onCreateViewFromTag --> onCreateView --> createView ,createView 中通过反射构建根 View 对象
  3. 获取到根 View 对象后,调用 rInflateChilder 方法,其中通过解析器循环解析根 View 中的子 View,方法依然通过 onCreateViewFromTag --> onCreateView --> createView ,createView 中通过反射构建 View 对象
  4. 循环解析到根 View 的子 View 后将通过相同方法递归调用解析子 View 中的元素,并将解析到的 View 回溯回来将其添加到 父 View 中
  5. 循环结束后,通过根 View 是否有父 View 为根 View 设置 xml 中设置的 LayoutParams
  6. 返回父 View 或者根 View
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容