资讯专栏INFORMATION COLUMN

记 LayoutInflater 源码流程

KitorinZero / 2706人阅读

摘要:而对于节点的处理情况是将其当做子进行处理,调用的都是函数,所以,我们讨论子实例化的时候可以一起讨论。首先是看第一部分,父布局的实例化。该部分参考下面的流程图,看起来更加清晰。对于整体的流程,我画了流程图,如下

走了一遍 LayoutInflater的流程,特此记录 获取 LayoutInflater --- LayoutInflater.from(context)

获取LayoutInflater对象实例

    public static LayoutInflater from(Context context) {
        //获取 layoutInflater,注意这是一个IPC的过程,获取的实例是PhoneLayoutInflater,与LayoutInflater 区别不大,重写了protected View onCreateView(String name, AttributeSet attrs) 函数,具体可以去看源码,位置是frameworks/base/core/java.com.android.internal.policy.impl
            LayoutInflater LayoutInflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //如果为空抛出错误       
            if (LayoutInflater == null) {
                throw new AssertionError("LayoutInflater not found.");
            }
        //返回值
                    return LayoutInflater;
    }

调用Inflate -- LayoutInflater.from(context).inflate(R.layout.activity_layout,null,false)
 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        //获取resource对象
        final Resources res = getContext().getResources();
        ...
        //把R.layout.activity_layout 放入,获取整个 Xml的Parser
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            // 开始真正的inflate
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)是整个inflate的核心部分

整体流程:
找到最外层的父级布局 ===》 处理merge节点情况 ===》实例化父级布局 ===》根据父级布局,调用rInflate函数去实例化子级view ===> 根据实例化结果,以及外部参数,进行view的添加以及结果的返回

    public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        //同步进入
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
            // 解析返回 attrs
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            // 
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            // 传入的 viewgroup 是 null
            View result = root;
            try {
                // 此处尝试寻找开始和结束节点,即找到整个layout的最外层 view
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                // 如果 type != 开始节点抛出错误,也就是说没找到开始节点
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            * ": No start tag found!");
                }
                // 获取当前节点的名字,也就是当前layout的根节点的名字
                final String name = parser.getName();
                
                ...
                //处理 merge 节点
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException(" can be used only with a valid "
                                * "ViewGroup root and attachToRoot=true");
                    }
                    rInflate(parser, root, attrs, false, false);
                } else {// 不是merge的情况下
                    // createViewFromTag 该方法是根据前面获取的 tag 的名字,创建具体的view对象
                    // 此处特殊的地方时,Temp 就是根节点,也就是整个layout的根节点,因为 name 是前面获取的根节点的名字
                    final View temp = createViewFromTag(root, name, attrs, false);
                    // 初始化 params
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {// root != 空,会初始化出一个 params
                        
                        ...
                        // 如果提供了root,会根据 root 创建 layout params 
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }
                    ...
                    // 此处,会进行所有的 temp 的子 view 的 inflate
                    rInflate(parser, temp, attrs, true, true);
                    
                    ...
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {
                ...
            } catch (IOException e) {
                ...
            } finally {
                // Don"t retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            return result;
        }
    }

其中整个流程中,核心部分分两点
1.实例化父级布局,
2.实例化子级view
而对于merge节点的处理情况是将其当做子view进行处理,调用的都是rInflate函数,所以,我们讨论子view实例化的时候可以一起讨论。

首先是看第一部分,父布局temp的实例化。

他是直接调用createViewFromTag,我们进入该函数。这个函数整体的流程是
处理特殊节点view ===》 对当前view的context进行初始化 ====》 特殊节点blink处理 ===》根据几个工厂对象(默认情况下,工程类都为null)实例化view ===》 工厂类创建失败,view == null,调用onCreateView()或者createView()view进行实例化

     View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
        // 特殊处理 `view` 节点
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }
        // 设置当前 view 的 context
        Context viewContext;
        if (parent != null && inheritContext) {
            // 如果父级 view 不为空 并且要求从父级 view 那里获取 context
            viewContext = parent.getContext();
        } else {
            // 否则 当前 view 的 context 等于 LayoutInflater.fromt(context) 中传入的 context
            viewContext = mContext;
        }
        // 如果有主题切换,那么就应用对应的主题
        final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
        final int themeResId = ta.getResourceId(0, 0);
        if (themeResId != 0) {
            viewContext = new ContextThemeWrapper(viewContext, themeResId);
        }
        ta.recycle();
        // blink 处理
        if (name.equals(TAG_1995)) {
            // Let"s party like it"s 1995!
            return new BlinkLayout(viewContext, attrs);
        }
        ...
        try {
            // 用工厂类创建真正的 view 对象
            // 默认两个工厂类都为 null
            // 所以 view 是 null
            View view;
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, viewContext, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, viewContext, attrs);
            } else {
                view = null;
            }
            // 在 view 用前面两个工厂类创建为 null 
            // 同时私有工厂类不为空的情况下,调用私有的工厂类创建 view 对象
            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
            }
            // 私有工厂创建依旧为 null 时
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = viewContext;
                try {
                    if (-1 == name.indexOf(".")) {// 如果是 Android 自带 view
                        view = onCreateView(parent, name, attrs);
                    } else {// 如果不是 Android 自带 view
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            ...
            return view;
        } catch (InflateException e) {
            ...
        } catch (ClassNotFoundException e) {
            ...
        } catch (Exception e) {
            ...
        }
    }

其中这个函数的核心部分则是onCreateView()createView(),因为默认情况下,几个factory都是null,所以都会进入这两个函数中的一个。

    if (-1 == name.indexOf(".")) {// 如果是 Android 自带 view
        view = onCreateView(parent, name, attrs);
    } else {// 如果不是 Android 自带 view
        view = createView(name, null, attrs);
    }

两个函数调用条件是,-1 == name.indexOf("."),而其效果则是,判断是否为Android自带 view,如果是,则调用onCreateView(),否则当做自定义view处理,调用createView()

先看onCreateView,该部分主要是对sClassPrefixList进行迭代,拼凑出整个view的路径,然后调用createView(),注意这个函数,和上面说的处理自定义viewcreateView(),是同一个函数,所以也就明白,为什么要有上面的判断了

    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };
     ....
     ....
     @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;
                }
            } catch (ClassNotFoundException e) {
                ...
            }
        }
        return super.onCreateView(name, attrs);
    }

然后我们看真正的动态创建出view对象的函数createView(String name, String prefix, AttributeSet attrs),该函数的作用就是,通过反射创建出真正的对象
其过程也很简单,直接在已经存在的sConstructorMap中找,是不是有这个名字,如果有就开始创建,没有就把前缀拼上去,再创建,然后放入sConstructorMap

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Constructor constructor = sConstructorMap.get(name);
        Class clazz = null;
        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
            if (constructor == null) {
                // Class not found in the cache, see if it"s real, and try to add it
                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);
                    }
                }
                constructor = clazz.getConstructor(mConstructorSignature);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);
                        
                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }
            Object[] args = mConstructorArgs;
            args[1] = attrs;
            constructor.setAccessible(true);
            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 (NoSuchMethodException e) {
            ...
        } catch (ClassCastException e) {
            ...
        } catch (ClassNotFoundException e) {
            ...
        } catch (Exception e) {
            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

然后是子布局的实例化

该部分内容,主要是对当前节点的所有view 进行遍历,然后调用createViewFromTag()(该方法上面已经有解释了)方法创建实例。如果遍历到某一个view,他是有子节点的,则递归调用函数rInflate()对该子节点进行遍历。该部分参考下面的流程图,看起来更加清晰。

    void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
            boolean finishInflate, boolean inheritContext) 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)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, parent, attrs, inheritContext);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, attrs, inheritContext);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true, true);
                viewGroup.addView(view, params);
            }
        }
        if (finishInflate) parent.onFinishInflate();
    }

===========================
以上就是 inflate 整个核心部分。

对于整体的流程,我画了流程图,如下


文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/13094.html

相关文章

  • LayoutInflater--替换系统控件

    摘要:之前记录了自己走通的源码整体流程,一直想搞个好玩的东西,想起之前看到过的换肤方案,决定写个换系统控件的库。以上三点拼在一起就可以进行系统控件的同意替换,具体重写的细节请参考源码。 之前记录了自己走通 LayoutInflater 的源码整体流程,一直想搞个好玩的东西,想起之前看到过的换肤方案,决定写个换系统控件的库。项目地址,项目的具体使用,可以看README 首先需要确定,Layo...

    duan199226 评论0 收藏0
  • LayoutInflater.inflate看View的创建过程

    摘要:将布局文件实例化为其对应的对象。回到第行,这个是最关键的函数调用,正是完成了的创建。第行是对的子标签进行处理,完成子的创建,然后在行,将子添加到中,最后方法会回调的方法,以此完成这个文件中的的创建过程。最后返回该对象,这样就完成了的创建。 从LayoutInflater.inflate看View的创建过程 背景: 在Activity中,我们通过在onCreate方法中调用setCont...

    cc17 评论0 收藏0
  • [安卓]ListView 与 RecyclerView的比较

    摘要:与在在应用非常广泛,相对于其他的来说比较复杂,接下来我将讲一下创建的流程以及两者的不同。首先肯定要先把仓库准备好腾一块地方出来,在布局中添加。把装水果的框子准备好,创建布局。主角登场啦,咱们的搬运工,创建类。ListView与RecyclerView在在app应用非常广泛,相对于其他的view(button textview)来说比较复杂,接下来我将讲一下创建的流程以及两者的不同。 代码...

    fantix 评论0 收藏0
  • LayoutInflater详解

    摘要:传入的值不同,会出现什么结果呢先初略解释下这两个参数指实例的布局所要放入的根视图。指是否附加到传入的根视图。如果不为,设为,会把添加到中,此时在布局文件中的根的属性会生效。 在日常开发中经常会用到通过资源id去获取view的场景,LayoutInflater这时非常有用。这与我们经常用的findViewById()不一样。 LayoutInflater通常用于动态载入的界面,使用La...

    leanote 评论0 收藏0
  • Android源码分析-setContentView加载布局流程

    摘要:上篇文章追溯了源码中的启动流程,那么启动之后,是如何加载布局的呢这篇文章我们继续来追溯这一块的源码。它创建了的,设置了的主题以及布局。最后将生成的树添加到的根布局上。这就是生成对象的流程。 上篇文章追溯了Android源码中Activity的启动流程,那么Activity启动之后,是如何加载布局的呢?这篇文章我们继续来追溯这一块的Android源码。 Activity->setCont...

    yanwei 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<