4.3 View的工作流程(一)

2016-06-22  本文已影响53人  武安长空

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

注意:这里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));
    }
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="qingfengmy.developmentofart._4view.ViewActivity">

    <qingfengmy.developmentofart._4view.DemoTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

问题确实存在,如果我们这样

@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宽高的方式

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus){
        // 得到焦点
        
    }
}
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        
    }
});
上一篇下一篇

猜你喜欢

热点阅读