ScrollView---------onMeasure解析

本文深入解析ScrollView在Android系统中的测量机制,包括MeasureSpec的理解及其在ScrollView中的应用,详细阐述了ScrollView如何影响子视图的大小及测量过程。

理解原理,阅读源码,否则你只是个机器

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //是否填满view视图,没有填满就不用滑动
        if (!mFillViewport) {
            return;
        }
        //获取mode;;;MeasureSpec是view的内部类 有三种模式
        //UNSPECIFIED--parent没有对child做任何限制,child想设置多大就设置多大
        //EXACTLY -- parent给child一个确定的大小,无论child怎么设置不能超过这个大小
        //AT_MOST--child可以得到它想要的大小
        //这里heightMeasureSpec来自父容器调用child.measure(widthMeasureSpec,heightMeasureSpec)
        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode == MeasureSpec.UNSPECIFIED) {
            return;
        }

注释比较详细,MeasureSpec可以查阅资料理解。这里首先调用父类的onMeasure,注意这里parent都是代表的父容器,super这里是FrameLayout。下面先看看父类的onMeasure方法

 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int count = getChildCount();//获取child数量 scrollview里面只有1个child
        //如果本身宽高都设置为match,则这里为true --- 这里不是父容器的值,因为你的scrollview
        //就算怎么放也肯定会放在另外一个容器里面,顶层容器为FrameLayout,而容器类调用child.
        //measure(childWidthMeasureSpec,childHeightMeasureSpec)这里模式值会调用child.param参数获得
        final boolean measureMatchParentChildren =
                MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
                MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
        mMatchParentChildren.clear();

        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0); //测量child
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);//找出child中宽度最大值
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);//找出child中高度最大值
                childState = combineMeasuredStates(childState, child.getMeasuredState());//合并两个状态 curState | newState
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);//如果这里FrameLayout设置match,就将child中是match属性的存起来
                    }
                }
            }
        }
具体在看下measureChildWithMargins()方法,这个方法来自于ViewGroup,FrameLayout并没有重写这个方法,Scrollview里面也有这个 方法先看下ViewGroup的这个方法。

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {//(child, widthMeasureSpec, 0, heightMeasureSpec, 0)
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
        //getChildMeasureSpec(int spec, int padding, int childDimension)
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
getChildMeasureSpec是ViewGroup的方法,得到的是child的MeasureSpec参数,返回了一个MeasureSpec.makeMeasureSpec(resultSize, resultMode);这里有几种关系:

1、parent是match,child是match ,那么child的size为parent的size减去 padding和child的margin大小,mode为MeasureSpec.EXACTLY

2、parent是match,child是wrap, 那么child的size为parent的size减去 padding和child的margin大小,mode为MeasureSpec.AT_MOST

3、parent是match,child是固定大小(如50dp) ,那么child的size为固定大(如50dp),mode为MeasureSpec.EXACTLY


4、parent是wrap,child是固定大小(如50dp) ,那么child的size为固定大(如50dp),mode为MeasureSpec.EXACTLY

5、parent是wrap,child是wrap或者match, 那么child的size为parent的size减去 padding和child的margin大小,mode为MeasureSpec.AT_MOST

6、如果parent的模式是UNSPECIFIED,这里忽略,具体可以看代码ViewGroup的getChildMeasureSpec方法

再看下ScrollView里面的这个方法

@Override
    protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = MeasureSpec.makeSafeMeasureSpec(
                MeasureSpec.getSize(parentHeightMeasureSpec), MeasureSpec.UNSPECIFIED);//这里给自己设置的高度就是parent的高度,但是模式是UNSPECIFIED

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

这里就是说ScrollView的child都给的这个模式UNSPECIFIED,具体看下如何构建MeasureSpec的吧:

/**
         * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
         * will automatically get a size of 0. Older apps expect this.
         *
         * @hide internal use only for compatibility with system widgets and older apps
         */
        public static int makeSafeMeasureSpec(int size, int mode) {
            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
                return 0;
            }
            return makeMeasureSpec(size, mode);
        }

如注释解释,处于MeasureSpec模式的将自动返回0;但是这个有个sUseZeroUnspecifiedMeasureSpec控制器,这个参数当手机系统处于6.0以上将等于false,6.0以下就为true.

// In M and newer, our widgets can pass a "hint" value in the size
            // for UNSPECIFIED MeasureSpecs. This lets child views of scrolling containers
            // know what the expected parent size is going to be, so e.g. list items can size
            // themselves at 1/3 the size of their container. It breaks older apps though,
            // specifically apps that use some popular open source libraries.
            sUseZeroUnspecifiedMeasureSpec = targetSdkVersion < M;

即当child测量时候 父类给的高度为0 模式为UNSPECIFIED(无限制),这个就是scrollview和其他容器的不同了 。这里为什么listview在ScrollView和LinearLayout里面显示的大小不一样的原因了。因为ScrollView里面child的高度是失效的,只能是自身的大小

其他的情况如下:

这里得到了的child的MeasureSpec参数,那么就进行child的measure;child的测量执行完呢,child应该设定了一个初步的大小。

那么这个大小是多少呢?

这里我们继续回到FrameLayout的onMeasure方法中,

 maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);//找出child中宽度最大值
这句中 child.getMeasureWidth应该返回的有一定的结果值了,这里就可以得到maxWidth和maxHeight了。继续看接下来的代码:

// Account for padding too
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // Check against our minimum height and width
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // Check against our foreground's minimum height and width
        final Drawable drawable = getForeground();
        if (drawable != null) {
            maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
            maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
        }

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                resolveSizeAndState(maxHeight, heightMeasureSpec,
                        childState << MEASURED_HEIGHT_STATE_SHIFT));//childState中宽度和高度 存储的位数不一样

这里对最大值进行加减padding的图片和背景图片做对比取出最大值;然后重点来了  根据这个最大值设置了一个测量大小,我们来看下resolveSizeAndState做了什么处理?

 public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
        final int specMode = MeasureSpec.getMode(measureSpec);
        final int specSize = MeasureSpec.getSize(measureSpec);
        final int result;
        switch (specMode) {
            case MeasureSpec.AT_MOST:
                if (specSize < size) {//如果是AT_MOST模式 就比较所需要的大小和parent给的大小,如果parent给的大小太小,就给个标志位MEASURED_STATE_TOO_SMALL
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
    }

具体可以看下这篇文章  讲这个state位和measureSpec位的情况 http://www.2cto.com/kf/201510/447521.html

虽然已经设置了大小,但是还有堆代码没分析 ,继续看看FrameLayout的onMeasure方法还做了什么?

count = mMatchParentChildren.size();
        if (count > 1) {
            for (int i = 0; i < count; i++) {
                final View child = mMatchParentChildren.get(i);
                final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

                final int childWidthMeasureSpec;
                if (lp.width == LayoutParams.MATCH_PARENT) {
                    final int width = Math.max(0, getMeasuredWidth()
                            - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                            - lp.leftMargin - lp.rightMargin);
                    childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                            width, MeasureSpec.EXACTLY);
                } else {
                    childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                            getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                            lp.leftMargin + lp.rightMargin,
                            lp.width);
                }

                final int childHeightMeasureSpec;
                if (lp.height == LayoutParams.MATCH_PARENT) {
                    final int height = Math.max(0, getMeasuredHeight()
                            - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                            - lp.topMargin - lp.bottomMargin);
                    childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                            height, MeasureSpec.EXACTLY);
                } else {
                    childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                            getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                            lp.topMargin + lp.bottomMargin,
                            lp.height);
                }

                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }

我们这里是ScrollView调用的FrameLayout的onMeasure方法,那么这里child就一个,所以这个if判断就不会进入。理一下思路,我们ScrollView 的onMeasure已经做了多少操作了?

1、调用父类的onMeasure已经设置了一个初步大小


继续:

 if (getChildCount() > 0) {
            final View child = getChildAt(0);//获取child,只有一个
            final int height = getMeasuredHeight();//在父类中设置
            if (child.getMeasuredHeight() < height) {//在父类中调用了child.measure,那么child也设置了一个值
                final int widthPadding;
                final int heightPadding;
                final FrameLayout.LayoutParams lp = (LayoutParams) child.getLayoutParams();
                final int targetSdkVersion = getContext().getApplicationInfo().targetSdkVersion;
                if (targetSdkVersion >= VERSION_CODES.M) {
                    widthPadding = mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin;
                    heightPadding = mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin;
                } else {
                    widthPadding = mPaddingLeft + mPaddingRight;
                    heightPadding = mPaddingTop + mPaddingBottom;
                }

                final int childWidthMeasureSpec = getChildMeasureSpec(
                        widthMeasureSpec, widthPadding, lp.width);
                final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(// 这里对宽度和高度的处理不一致
                        height - heightPadding, MeasureSpec.EXACTLY);
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }

很混乱 勿看,后面自己还需要梳理,暂时记在这里


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值