美文网首页
Android LayoutInflater

Android LayoutInflater

作者: 折剑游侠 | 来源:发表于2020-01-19 16:00 被阅读0次

我们常用LayoutInflater加载xml布局文件,adapter中没少写,下面看看源码流程。

LayoutInflater.from()

    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;
    }

context.getSystemService(LAYOUT_INFLATER_SERVICE),LayoutInflater本质上是一个系统服务。

LayoutInflater.inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

    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) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

adapter中加载布局,root-->parent,attachToRoot-->false。

XmlResourceParser继承自XmlPullParser-->解析xml的工具类。

LayoutInflater.inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {  
            ...
            View result = root;

            try {
                ...
                //处理merge标签,没有父View,或者attachToRoot为false没有意义,抛出异常
                if (TAG_MERGE.equals(name)) {
                    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 {
                    //创建xml布局中的顶层View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }

                    //创建子View
                    rInflateChildren(parser, temp, attrs, true);
                    
                    //父View不为null且attachToRoot为true-->xml布局需要添加到父View
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    //父View为null或attachToRoot为false-->xml布局无父View需要关联
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } 
            ...
            return result;
        }
    }

inflate()最终有两个流程分支

  • root != null && attachToRoot
    将xml布局View树当做子View添加到root,并返回root
  • root == null || !attachToRoot
    直接返回xml布局View树

inflate()方法调用链,LayoutInflater.createViewFromTag()

    private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
        return createViewFromTag(parent, name, context, attrs, false);
    }

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

        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)) {
            return new BlinkLayout(context, attrs);
        }

        try {
            View view;
            //各种Factory都可以对View进行扩展
            //可自行设置Factory,拦截创建View过程。
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            //无Factory直接生成View
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //名字包含'.'是自定义View,否则为系统原生View
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } 
    }

LayoutInflater.onCreateView()

    protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }

    protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, "android.view.", attrs);
    }
    
    public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        //判断view的构造器是否已缓存
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            //构造器不存在,反射获取构造器并缓存到map
            if (constructor == null) {
                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);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                //构造器已存在,loadclass加载view的class对象
                if (mFilter != null) {
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        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);
                    }
                }
            }
            ...
            //构造器创建view对象
            final View view = constructor.newInstance(args);
            ...
            return view;

        } 
    }

LayoutInflater.rInflateChildren(...)

    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

LayoutInflater.rInflate(...)

    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        ...
        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)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }
        ...
    }

rInflate()对各种标签进行处理,调用createViewFromTag()生成View实例。如果View是ViewGroup则继续调用rInflateChildren()生成子View实例并添加到View,直到View树全部实例化。

最后捋一捋流程:首先通过LayoutInflater.from()获取系统服务LAYOUT_INFLATER_SERVICE--->LayoutInflater实例;调用LayoutInflater.inflate()解析xml文件,创建xml中顶层View;调用createViewFromTag()->createView()反射生成View实例,createView()会缓存View构造器,优化反射的频繁调用;ViewGroup继续调用rInflateChildren()->createView()创建子View并添加到父View。递归调用,直到View树中所有View创建完毕。

相关文章

网友评论

      本文标题:Android LayoutInflater

      本文链接:https://www.haomeiwen.com/subject/vierzctx.html