android view

178 阅读4分钟

view绘制的时机

在view的结构中,顶层view是DecorView

    public void setContentView(int layoutResID) {
        
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }
    }
    private DecorView mDecor;
    private void installDecor() {
        if (mDecor == null) {
            mDecor = generateDecor(-1);
        }
    }

在activity启动的时候,ActivityThread.handleResumeActivity()方法中,decorView和ViewRoot建立关系(在activity的启动中在描述)。后面view的绘制都是由ViewRoot处理。

ViewRoot 流程

public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

scheduleTraversals方法一路追踪下去:
scheduleTraversals -> mTraversalRunnable -> doTraversal -> performTraversals

view 的绘制流程就是在performTraversals中描述的.

private void performTraversals() {
    
    boolean layoutRequested = mLayoutRequested && (!mStopped || mReportNextDraw);
    //测量
    if (layoutRequested) {
        measureHierarchy(host, lp, res, desiredWindowWidth, desiredWindowHeight);
    }
    //布局
    final boolean didLayout = layoutRequested && (!mStopped || mReportNextDraw);
    if (didLayout) {
        performLayout(lp, mWidth, mHeight);
    }
    
    //绘制
    boolean cancelDraw = mAttachInfo.mTreeObserver.dispatchOnPreDraw() || !isViewVisible;
    if (!cancelDraw && !newSurface) {
        performDraw();
    }

}

MeasureSpec

private boolean measureHierarchy(final View host, final WindowManager.LayoutParams lp,
            final Resources res, final int desiredWindowWidth, final int desiredWindowHeight) {
			
		int childWidthMeasureSpec;
		int childHeightMeasureSpec;
		boolean windowSizeMayChange = false;
		boolean goodMeasure = false;
		
		if (!goodMeasure) {
		        childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
		        childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
		        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
	            if (mWidth != host.getMeasuredWidth() || mHeight != host.getMeasuredHeight()) {
		                windowSizeMayChange = true;
	            }
		}
		
		return windowSizeMayChange;
}

获取根View(decorView)宽高的约束信息:

private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // 
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

针对 layout_width 或者 layout_height使用的数值:

  • EXACTLY 使用match_parent或者精确数值时,子view的大小时确定的,就是SpecSize
  • AT_MOST 使用wrap_content的时候,子View最大不能超过父View的SpecSize
  • UNSPECIFIED 对子view不做限制,上层通常不使用。

对于根decorView,是根据屏幕的大小和自身的LayoutParams来确定自身大小的,其他的view都是根据父布局的MeasureSpec和自身的LayoutParams来确定自身大小。

measure

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

调用根view的measure方法

View:
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));
    }

onMeasure方法主要是根据传进来的宽高约束参数来计算view本身的宽高,然后通过setMeasuredDimension进行设置。

现在看看DecorView的onMeasure方法:

public class DecorView extends FrameLayout{

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

measure流程

DecorView的onMeasure方法调用了父亲FrameLayout的onMeasure。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        // 计算所有子View的最大宽度和最大高度
        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                // 计算margin
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

        // 计算padding
        maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
        maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

        // 计算mBackground
        maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        // 计算前景
        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));
        
        // 调用所有child的measure方法
        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);
            }
        }
}
  • measure是从ViewGroup开始向下一层层计算。
  • measure的时候使用margin和layoutparams一起来计算

ViewGroup是没有onMeasure方法的,所以我们在继承ViewGroup的时候一定要重写onMeasure方法,来计算控件的大小。否则不会计算子View的大小。

Layout

private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
            int desiredWindowHeight) {
        final View host = mView;
        // 调用View的layout 方法
        host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
            
}

View.layout

public void layout(int l, int t, int r, int b) {
    onLayout(changed, l, t, r, b);
}
// 如果是ViewGroup的话就重写该方法,对所有的child进行布局
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}

看下DecorView的实现

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        layoutChildren(left, top, right, bottom, false /* no force left gravity */);
    }
    
}

void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {

    final int count = getChildCount();

        final int parentLeft = getPaddingLeftWithForeground();
        final int parentRight = right - left - getPaddingRightWithForeground();

        final int parentTop = getPaddingTopWithForeground();
        final int parentBottom = bottom - top - getPaddingBottomWithForeground();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();

                final int width = child.getMeasuredWidth();
                final int height = child.getMeasuredHeight();

                int childLeft;
                int childTop;

                int gravity = lp.gravity;
                if (gravity == -1) {
                    gravity = DEFAULT_CHILD_GRAVITY;
                }

                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                        lp.leftMargin - lp.rightMargin;
                        break;
                    case Gravity.RIGHT:
                        if (!forceLeftGravity) {
                            childLeft = parentRight - width - lp.rightMargin;
                            break;
                        }
                    case Gravity.LEFT:
                    default:
                        childLeft = parentLeft + lp.leftMargin;
                }

                switch (verticalGravity) {
                    case Gravity.TOP:
                        childTop = parentTop + lp.topMargin;
                        break;
                    case Gravity.CENTER_VERTICAL:
                        childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                        lp.topMargin - lp.bottomMargin;
                        break;
                    case Gravity.BOTTOM:
                        childTop = parentBottom - height - lp.bottomMargin;
                        break;
                    default:
                        childTop = parentTop + lp.topMargin;
                }

                // 调用child的layout方法
                child.layout(childLeft, childTop, childLeft + width, childTop + height);
            }
        }
}

draw

private void performDraw() {
     draw(fullRedrawNeeded);
}

private void draw(boolean fullRedrawNeeded) {
    if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
                    return;
                }
}

private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
            boolean scalingRequired, Rect dirty) {
            // 调用View的draw方法进行绘制
            mView.draw(canvas);
}

View.draw

public void draw(Canvas canvas) {
    // 1. 绘制View自身背景
    drawBackground(canvas);
    // 2. 绘制View自身内容
    if (!dirtyOpaque) onDraw(canvas);
    // 3. 绘制子View,viewGroup中要实现
    dispatchDraw(canvas);
    // 4. 绘制前景或者scrollbar
    onDrawForeground(canvas);
}

onDraw方法是绘制自身,但是默认是空方法,要自己实现

 protected void onDraw(Canvas canvas) {
 }
    

通过上面可以看到绘制一个view需要几个核心的方法:

  • onMeasure 不包含子view的话,可以不重写该方法。但是如果使用wrap_content的话,有可能要重写,手动计算高度。ViewGroup的话必须要实现该方法,去测量每个child。
  • onLayout 不包含子view的话,可以不重写该方法,ViewGroup要重写,去针对每个子view进行布局。
  • onDraw 该方法是哥空方法,所以单个View和ViewGroup都必须要实现该方法。