关于include、merge、ViewStub的那点事

相信大家已经对这三位大哥不陌生了。

  • include:一般xml代码View的复用,减少同样布局的cv操作
  • merge:提高xml的View组件复用,且减少不必要层级
  • ViewStub:某些View不是必须加载的,通过ViewStub实现延时加载

通过LayoutInflater分析include和merge

总所周知xml布局代码,最终会调用LayoutInflater.inflate方法。先去看下inflate()具体流程。所以include和merge直接通过LayoutInflater去解析更加清晰明了

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
//无关代码将会省略,展示代码并非LayoutInflater.inflate方法所有代码
        synchronized (mConstructorArgs) {
            try {
                if (TAG_MERGE.equals(name)) {
                    //inflate Merge标签下的所有View
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                   
                    //解析xml中的View,最终回落rInflate
                    rInflateChildren(parser, temp, attrs, true);
                    
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }
                  
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            }//忽略相关catch代码

            return result;
        }
    }

可以看到inflate代码逻辑比较简单,如果是merge标签则通过rInflate方法解析merge所有view。否则通过rInflateChildren方法去解析,而rInflateChildren最终调用rInflate方法。

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

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        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(" cannot be the root element");
                }
                //解析include标签-----
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" must be the root element");
            } else {
                //merge标签最终回落到这里---------
                final View view = createViewFromTag(parent, name, context, attrs);
                //merge标签最终布局为其调用的父布局
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //继续inflate其children view
                rInflateChildren(parser, view, attrs, true);
                // 添加至父布局
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

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

从上面可以看出merge最终会将merge中所有view添加至父布局中。

而include标签最终起调parseInclude方法。

    private void parseInclude(XmlPullParser parser, Context context, View parent,
            AttributeSet attrs) throws XmlPullParserException, IOException {
        int type;

        if (parent instanceof ViewGroup) {//include 最外层元素必须要viewgroup类型
          
            int layout = attrs.getAttributeResourceValue(null, ATTR_LAYOUT, 0);
            if (layout == 0) {
                layout = context.getResources().getIdentifier(
                        value.substring(1), "attr", context.getPackageName());
            }

            if (layout == 0) {
                throw new InflateException("You must specify a valid layout "
                        + "reference. The layout ID " + value + " is not valid.");
            } else {
                final XmlResourceParser childParser = context.getResources().getLayout(layout);

                try {
                    final AttributeSet childAttrs = Xml.asAttributeSet(childParser);

                    if (TAG_MERGE.equals(childName)) {
                        // The  tag doesn't support android:theme, so
                        // nothing special to do here.
                        rInflate(childParser, parent, context, childAttrs, false);
                    } else {
                        final View view = createViewFromTag(parent, childName,
                                context, childAttrs, hasThemeOverride);
                        final ViewGroup group = (ViewGroup) parent;

                        final TypedArray a = context.obtainStyledAttributes(
                                attrs, R.styleable.Include);
                        final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
                        final int visibility = a.getInt(R.styleable.Include_visibility, -1);
                        a.recycle();

                        //优先使用父布局中的layout信息,没有的话使用include中的信息
                        ViewGroup.LayoutParams params = null;
                        try {
                            params = group.generateLayoutParams(attrs);
                        } catch (RuntimeException e) {
                        }
                        if (params == null) {
                            params = group.generateLayoutParams(childAttrs);
                        }
                        view.setLayoutParams(params);

                        // Inflate all children.
                        rInflateChildren(childParser, view, childAttrs, true);
                       //若父布局中有id则覆盖include内的id
                        if (id != View.NO_ID) {
                            view.setId(id);
                        }
                        group.addView(view);
                    }
                } finally {
                    childParser.close();
                }
            }
        } else {
            throw new InflateException(" can only be used inside of a ViewGroup");
        }

        LayoutInflater.consumeChildElements(parser);
    }

这里可以看出include布局中的宽高信息及id默认使用父布局定义的。所以include中定义的id及宽高信息会被调用的父布局定义给覆盖。且父布局中也只能定义对应的LayoutParams信息。

ViewStub

public final class ViewStub extends View

可以看出ViewStub本质上还是一个view。只是在构建方法中默认将自己设为GON及忽略了绘制过程,并且在measure时默认将自己设为0像素大小

    public void setVisibility(int visibility) {
        if (mInflatedViewRef != null) {
            View view = mInflatedViewRef.get();
            if (view != null) {
                view.setVisibility(visibility);
            } else {
                throw new IllegalStateException("setVisibility called on un-referenced view");
            }
        } else {
            super.setVisibility(visibility);
            if (visibility == VISIBLE || visibility == INVISIBLE) {
                inflate();
            }
        }
    }

    public View inflate() {
        final ViewParent viewParent = getParent();

        if (viewParent != null && viewParent instanceof ViewGroup) {
            if (mLayoutResource != 0) {
                final ViewGroup parent = (ViewGroup) viewParent;
                //inflate 指定的layout
                final View view = inflateViewNoAdd(parent);
                //移除自己并将inflate的View添加进parent中
                replaceSelfWithView(view, parent);

                mInflatedViewRef = new WeakReference<>(view);
                if (mInflateListener != null) {
                    mInflateListener.onInflate(this, view);
                }

                return view;
            } else {
                throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
            }
        } else {
            throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
        }
    }

可以看出通过setVisibility且visibility == VISIBLE || visibility == INVISIBLE时也是会起调inflate()方法进行懒加载。
inflate过后ViewStub的parent将为空,所以可以通过ViewStub.getParent()是否等于空去判断ViewStub是否已经inflate,或者通过setOnInflateListener去监听。

你可能感兴趣的:(关于include、merge、ViewStub的那点事)