4.3|4.3 View的工作流程(一)

1. View的measure过程 measure是final的,但它里面调用了onMeasure方法

public final void measure(int widthMeasureSpec, int heightMeasureSpec) { ... onMeasure(widthMeasureSpec, heightMeasureSpec); }

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }

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: // unspecified是getSuggestedMinimumWidth()的size result = size; break; case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: // 精确模式和最大模式的测量宽高都是MeasureSpec中的size result = specSize; break; } return result; }

protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); }

如果有背景则返回背景宽度,否则返回mMinWidth值,mMinWidth是android:minWidth的这个属性值所指定的值,没有指定则为0.而mBackground为drawable类型,获取背景宽度如下
public int getMinimumWidth() { final int intrinsicWidth = getIntrinsicWidth(); return intrinsicWidth > 0 ? intrinsicWidth : 0; }

有原始宽度,则返回原始宽度,否则返回0。那么Drawable在什么情况下有原始宽度?ShapeDrawable就没有原始宽度,BitmapDrawable就有原始宽度。
再看setMeasuredDimension方法
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) { ... setMeasuredDimensionRaw(measuredWidth, measuredHeight); }

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) { mMeasuredWidth = measuredWidth; mMeasuredHeight = measuredHeight; mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET; }

【4.3|4.3 View的工作流程(一)】注意:这里mMeasuredWidth和mMeasuredHeight就是最终的测量宽高值
2. 一个问题 从上面的分析中可以知道,View的宽高由specSize决定,所以我们可以得出如下结论:直接继承View的自定义控件要重写onMeasure方法并设置wrap_content时的自身大小,否则在布局中使用wrap_content就相当于使用match_parent。
首先写个例子试一下:
public class DemoTextView extends View { public DemoTextView(Context context, AttributeSet attrs) { super(context, attrs); setBackgroundColor(getResources().getColor(android.R.color.holo_blue_bright)); } }


问题确实存在,如果我们这样
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(200,200); }

则View的宽高就是200。但TextView却是正常的,可见这些具体的View都已经重写在onMeasure方法,下面简单看下TextView的onMeasure代码
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else { final Drawables dr = mDrawables; if (dr != null) { width = Math.max(width, dr.mDrawableWidthTop); width = Math.max(width, dr.mDrawableWidthBottom); }width += getCompoundPaddingLeft() + getCompoundPaddingRight(); }if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; mDesiredHeightAtMeasure = -1; } else { if (heightMode == MeasureSpec.AT_MOST) { height = Math.min(desired, heightSize); } }int unpaddedHeight = height - getCompoundPaddingTop() - getCompoundPaddingBottom(); setMeasuredDimension(width, height); }

3. ViewGroup的measure过程
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) { final int size = mChildrenCount; final View[] children = mChildren; for (int i = 0; i < size; ++i) { final View child = children[i]; if ((child.mViewFlags & VISIBILITY_MASK) != GONE) { measureChild(child, widthMeasureSpec, heightMeasureSpec); } } }

protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { final LayoutParams lp = child.getLayoutParams(); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft + mPaddingRight, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop + mPaddingBottom, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); }

ViewGroup没有定义其测量的具体过程,因为ViewGroup是一个抽象类,其测量过程的onMeasure方法需要各个子类去具体实现,这也是因为不同的ViewGroup子类有不同的布局特性,因此ViewGroup无法做统一实现。
4. LinearLayout的onMeasure方法
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mOrientation == VERTICAL) { measureVertical(widthMeasureSpec, heightMeasureSpec); } else { measureHorizontal(widthMeasureSpec, heightMeasureSpec); } }

void measureVertical(int widthMeasureSpec, int heightMeasureSpec) { final int count = getVirtualChildCount(); final int widthMode = MeasureSpec.getMode(widthMeasureSpec); final int heightMode = MeasureSpec.getMode(heightMeasureSpec); for (int i = 0; i < count; ++i) { // 遍历每个child final View child = getVirtualChildAt(i); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams(); if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) { final int totalLength = mTotalLength; mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin); } else { int oldHeight = Integer.MIN_VALUE; if (lp.height == 0 && lp.weight > 0) { oldHeight = 0; lp.height = LayoutParams.WRAP_CONTENT; }measureChildBeforeLayout( child, i, widthMeasureSpec, 0, heightMeasureSpec, totalWeight == 0 ? mTotalLength : 0); final int childHeight = child.getMeasuredHeight(); final int totalLength = mTotalLength; // 每次都叠加新的高度 mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin + lp.bottomMargin + getNextLocationOffset(child)); } } // 算LinearLayout自己的高度 setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState); }

如果它的布局中的高度采用的match_parent或者具体值,那么高度为specSize;如果它的布局中高度采用的wrap_content,那么它的高度是所有元素的高度总和,但不能超过父容器的剩余空间。
5. 几种获取View宽高的方式
  • onWindowFocusChanged方法
    当Activity的窗口在得到焦点和失去焦点时均会被调用一次。
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus){ // 得到焦点} }

  • view.post
    延时获取
  • ViewTreeObserver
    当View树的状态发生或者改变View树内部的View可见性时,onGlobalLayout将会被调用。随着View树的状态改变,onGlobalLayout会多次调用。
ViewTreeObserver observer = view.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() {} });

  • view.measure
    手动通过measure方法来得到View的宽高,根据LayoutParams来分:
    • match_parent
      直接放弃,因为这种需要知道parentSize,我们无法知道,所以直接放弃。
    • 固定像素值
    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY); view.measure(widthMeasureSpec,heightMeasureSpec);

    • wrap_content
    int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST); int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST); view.measure(widthMeasureSpec,heightMeasureSpec);

    注意上面的(1<<30)-1,因为是最大化,所以宽高值应该是最大值,而specSize最大是30ge1,也就是(1<<30)-1.

    推荐阅读