-
概述
我们知道,在整个布局渲染流程中,系统提供给我们可以自定义的有三个方法:onMeasure、onLayout和onDraw。在开发过程中,大多数时候我们不需要重写这三个方法,因为我们使用的容器类组件都实现了相关的方法,比如LinearLayout为何会自动把子View按线性排列,RelativeLayout为何能根据其他View的位置安排子View的位置,wrap_content又是如何根据子View的总大小决定的等等,这些都是根据容器类组件重写的这几个方法计算的,onDraw方法通常是View组件会去重写的,有的容器类组件也会实现,比如LinearLayout会重写onDraw方法来绘制Divider。
下面通过官方的这些容器类的相关方法的实现来分析一下这些方法的原理。
-
ViewRootImpl
ViewRootImpl中的performLayout中调用了host.layout方法,layout方法中先后调用onMeasure和onLayout方法。
ViewRootImpl中的performDraw方法调用了draw方法,最终调用到View的onDraw方法。
performLayout和performDraw都是在performTraversals中调用的,performTraversals就是布局流程的逻辑入口。
-
onMeasure方法
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }
上面是这个方法在View中的默认实现,它有两个Integer型参数,widthMeasureSpec和heightMeasureSpec分别表示宽度参数和高度参数,每一个参数中都有两个信息,一个是模式,一个是大小,大小是父容器传给他的约束尺寸,这个会根据模式决定,比如wrap_content的时候约束大小是0,模式是LayoutParams中指定的:
/** * Measure specification mode: The parent has not imposed any constraint * on the child. It can be whatever size it wants. */ //表示不确定的大小 public static final int UNSPECIFIED = 0 << MODE_SHIFT; /** * Measure specification mode: The parent has determined an exact size * for the child. The child is going to be given those bounds regardless * of how big it wants to be. */ //表示精确的大小,比如设置了具体的尺寸、match_parent public static final int EXACTLY = 1 << MODE_SHIFT; /** * Measure specification mode: The child can be as large as it wants up * to the specified size. */ //表示根据子View的总大小来决定 public static final int AT_MOST = 2 << MODE_SHIFT;
我想说明的是,这三个模式都只是标志,也就是说即使是判断LayoutParams是EXACTLY,你也可以设置子View总大小为最终测量大小,只不过这样以来就混乱了,说到底,这里的模式是规矩,你按照这些规矩决定怎么去测量、采用哪组测量数据。
最终要调用setMeasuredDimension方法设置测量尺寸,最终会调用setMeasuredDimensionRaw方法:
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { mMeasuredWidth = measuredWidth; mMeasuredHeight = measuredHeight; mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; }
可以看到,测量大小会保存在mMeasuredWidth和mMeasuredHeight。
默认实现的测量大小通过getDefaultSize方法获得:
public static int getDefaultSize(int size, int measureSpec) { int result = size; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); switch (specMode) { case MeasureSpec.UNSPECIFIED: result = size; break; case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = specSize; break; } return result; }
可以看到,如果是不确定的大小就使用getSuggestedMinimumWidth方法返回值作为最终尺寸:
protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); }
可见,最小尺寸是取设置的minWidth的值和background的尺寸中较小的值,其他模式使用父容器给的约束尺寸。
再来看一个子类容器的实现,以LinearLayout为例:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mOrientation == VERTICAL) { measureVertical(widthMeasureSpec, heightMeasureSpec); } else { measureHorizontal(widthMeasureSpec, heightMeasureSpec); } }
以纵向排列为例,看一下measureVertical方法,部分截取代码如下:
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) { // See how tall everyone is. Also remember max width. for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); if (child == null) { mTotalLength += measureNullChild(i); continue; } //不可见的不测量 if (child.getVisibility() == View.GONE) { i += getChildrenSkipCount(child, i); continue; } //加上分割线的高度 if (hasDividerBeforeChildAt(i)) { mTotalLength += mDividerHeight; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); //这里是筛选出EXACTLY模式下LayoutParams含有weight配置的child,这些child此处暂不测量 final boolean useExcessSpace = lp.height == 0 && lp.weight > 0; if (heightMode == MeasureSpec.EXACTLY && useExcessSpace) { //测量模式是EXACTLY且有的View配置了weight属性 final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin); skippedMeasure = true; } else {//其他模式或者EXACTLY模式下未配置weight的情况下 final int usedHeight = totalWeight == 0 ? mTotalLength : 0; //测量每个View的大小 measureChildBeforeLayout(child, i, widthMeasureSpec, 0, heightMeasureSpec, usedHeight); //获取View的测量高度 final int childHeight = child.getMeasuredHeight(); final int totalLength = mTotalLength; //加上所有View的高度 mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child)); } } if (nonSkippedChildCount > 0 && hasDividerBeforeChildAt(count)) { mTotalLength += mDividerHeight; } // Add in our padding mTotalLength += mPaddingTop + mPaddingBottom; int heightSize = mTotalLength; // Reconcile our calculated size with the heightMeasureSpec int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0); heightSize = heightSizeAndState & MEASURED_SIZE_MASK; int remainingExcess = heightSize - mTotalLength + (mAllowInconsistentMeasurement ? 0 : consumedExcessSpace); //下面的测量就是针对EXACTLY模式下含有weight属性大于0的那些child if (skippedMeasure || ((sRemeasureWeightedChildren || remainingExcess != 0) && totalWeight > 0.0f)) { float remainingWeightSum = mWeightSum > 0.0f ? mWeightSum : totalWeight; mTotalLength = 0; for (int i = 0; i < count; ++i) { final View child = getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } final LayoutParams lp = (LayoutParams) child.getLayoutParams(); final float childWeight = lp.weight; if (childWeight > 0) { final int childHeight; if (mUseLargestChild && heightMode != MeasureSpec.EXACTLY) { childHeight = largestChildHeight; } else if (lp.height == 0 && (!mAllowInconsistentMeasurement || heightMode == MeasureSpec.EXACTLY)) { // This child needs to be laid out from scratch using // only its share of excess space. childHeight = share; } else { // This child had some intrinsic height to which we // need to add its share of excess space. childHeight = child.getMeasuredHeight() + share; } final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec( Math.max(0, childHeight), MeasureSpec.EXACTLY); final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec, mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin, lp.width); //测量大小 child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } final int totalLength = mTotalLength; //把所有View的高度加上 mTotalLength = Math.max(totalLength, totalLength + child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child)); } // Add in our padding mTotalLength += mPaddingTop + mPaddingBottom; // TODO: Should we recompute the heightSpec based on the new total length? } else { //这里是处理非EXACTLY的模式时,含有weight属性的child都采用上面测量中得知的最大高度作为他们的高度 if (useLargestChild && heightMode != MeasureSpec.EXACTLY) { for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child == null || child.getVisibility() == View.GONE) { continue; } final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); float childExtra = lp.weight; if (childExtra > 0) { child.measure( MeasureSpec.makeMeasureSpec(child.getMeasuredWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(largestChildHeight, MeasureSpec.EXACTLY)); } } } } maxWidth += mPaddingLeft + mPaddingRight; // Check against our minimum width maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); }
可以看到,这里会调用每个子View的onMeasure方法测量它们的大小,然后因为是纵向LinearLayout,按照这个容器的布局目的,所以会用子View中最大的那个宽度作为容器宽度,而容器的高度就等于所有子View的高度之和(当然还包括Divider的总高度和margin、padding)。
由此可知,对于ViewGroup来说,如果测量模式指定的是AT_MOST时,我们重写onMeasure时有两个要点:一个是需要先调用每个子View的onMeasure方法测量出大小,然后调用getMeasuredWidth或getMeasuredHeight方法获取每一个View的大小;一个是要根据容器的布局效果去决定如何利用这些子View的大小计算出容器的大小。
关于这一点,在RecyclerView中的测量方法里也是类似的。
-
onLayout方法
onMeasure方法其实是用来测量View本身的大小的,哪怕是ViewGroup也只是通过子View的大小来计算自己的大小,它本身并不决定子View是如何测量的。
而onLayout方法恰恰相反,他不是决定他自己被放置在哪里,他决定的是它的子View们在他的区域是如何放置的,在这里他会调用每一个子View的layout方法,传入参数告诉子View在哪个区域放置,然后一直递归,知道最后一个View。
onLayout方法没有默认实现,我们还是来看LinearLayout的onLayout方法:
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (mOrientation == VERTICAL) { layoutVertical(l, t, r, b); } else { layoutHorizontal(l, t, r, b); } }
第一个参数是父容器传过来的表示父容器给约束的区域是否发生了变化,后面四个参数是约束区域的四个边界,它们围成的区域就是子View可以放置的区域。
同样我们看纵向布局的布局方法layoutVertical:
void layoutVertical(int left, int top, int right, int bottom) { final int paddingLeft = mPaddingLeft; int childTop; int childLeft; // Where right end of child should go final int width = right - left; int childRight = width - mPaddingRight; // Space available for child int childSpace = width - paddingLeft - mPaddingRight; final int count = getVirtualChildCount(); final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK; final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK; //这里决定纵向上的放置对齐方式,决定top switch (majorGravity) { case Gravity.BOTTOM: // mTotalLength contains the padding already childTop = mPaddingTop + bottom - top - mTotalLength; break; // mTotalLength contains the padding already case Gravity.CENTER_VERTICAL: childTop = mPaddingTop + (bottom - top - mTotalLength) / 2; break; case Gravity.TOP: default: childTop = mPaddingTop; break; } //开始放置子View for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child == null) { childTop += measureNullChild(i); } else if (child.getVisibility() != GONE) { final int childWidth = child.getMeasuredWidth(); final int childHeight = child.getMeasuredHeight(); final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); int gravity = lp.gravity; if (gravity < 0) { gravity = minorGravity; } final int layoutDirection = getLayoutDirection(); final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection); //根据水平对齐标志决定left switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) { case Gravity.CENTER_HORIZONTAL: childLeft = paddingLeft + ((childSpace - childWidth) / 2) + lp.leftMargin - lp.rightMargin; break; case Gravity.RIGHT: childLeft = childRight - childWidth - lp.rightMargin; break; case Gravity.LEFT: default: childLeft = paddingLeft + lp.leftMargin; break; } if (hasDividerBeforeChildAt(i)) { childTop += mDividerHeight; } childTop += lp.topMargin; //调用child的layout方法 setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child); i += getChildrenSkipCount(child, i); } } }
setChildFrame方法内部会调用child的layout方法:
private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); }
layout的部分代码如下:
public void layout(int l, int t, int r, int b) { if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) { onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec); mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } int oldL = mLeft; int oldT = mTop; int oldB = mBottom; int oldR = mRight; boolean changed = isLayoutModeOptical(mParent) ? setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b); if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) { onLayout(changed, l, t, r, b); ... } ... }
可见这里会执行下一级的layout流程。
综上可知,onLayout方法中,最关键的就是决定每个子View的上下左右四个边界,然后传给他们的layout方法。
-
onDraw方法
onDraw方法主要是Canvas、Path和Paint的使用,关于它们的使用又需要很长的说明,详细的我就不讲了,我们这里整理的是流程原理,所以此时我们只需要知道这个方法是用来绘制View的内容的就可以了。有兴趣的可以去TextView看一下是怎么显示文本的来感受一下它们的用法。
网友评论