Android進階(五)View繪製流程

猥瑣發育_別浪發表於2019-02-02

一、Activity的setContentView

1、setContentView

#Activity
public void setContentView(@LayoutRes int layoutResID) {
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

public void setContentView(View view) {
    getWindow().setContentView(view);
    initWindowDecorActionBar();
}
複製程式碼

可以傳遞一個layout佈局檔案或者View,最終都是呼叫了getWindow()中的setContentView的相關方法。

getWindow返回什麼?
getWindow返回的Window實現類PhoneWindow,該物件是在Activity的attach方法中建立的

2、DecorView基本概念

#PhoneWindow
@Override
public void setContentView(int layoutResID) {

    if (mContentParent == null) {
        //(1)建立DecorView
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
        //(2)將acvivity的檢視新增到DecorView的mContentParent中
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
    mContentParentExplicitlySet = true;
}
複製程式碼

DecorView是一個FrameLayout,是Activity的頂級view,包含標題欄和內部欄。最終也是將Activity的佈局View新增到DecorView的內部欄中。

3、DecorView建立

通過installDecor進行DecorView的建立,內部呼叫了generateDecor方法建立了DecorView。

#PhoneWindow
protected DecorView generateDecor(int featureId) {
    ......
    return new DecorView(context, featureId, this, getAttributes());
}
複製程式碼

4、DecorView新增

在Activity展示過程中呼叫到ActivityThread的handleResumeActivity方法

final void handleResumeActivity(IBinder token,
    boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
    ......
    if (r.window == null && !a.mFinished && willBeVisible) {
        r.window = r.activity.getWindow();
        //(1)獲取到DecorView
        View decor = r.window.getDecorView();
        decor.setVisibility(View.INVISIBLE);
        ViewManager wm = a.getWindowManager();
        WindowManager.LayoutParams l = r.window.getAttributes();
        a.mDecor = decor;
        l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
        l.softInputMode |= forwardBit;
        if (r.mPreserveWindow) {
            a.mWindowAdded = true;
            r.mPreserveWindow = false;
           
            ViewRootImpl impl = decor.getViewRootImpl();
            if (impl != null) {
                impl.notifyChildRebuilt();
            }
        }
        if (a.mVisibleFromClient) {
            if (!a.mWindowAdded) {
                a.mWindowAdded = true;
                //(2)然後通過WindowManager實現了DecorView的新增
                wm.addView(decor, l);
        ......
        }

}
複製程式碼

5、ViewRootImpl

在WindowManager新增DecorView過程中,呼叫了ViewRootImpl的requestLayout方法,最終呼叫到了ViewRootImpl的performTraversals方法。 每一個Window都對應著一個View和一個ViewRootImpl,Window和View通過ViewRootImpl來建立聯絡。

#ViewRootImpl
private void performTraversals() {
    ......
   
    if (!mStopped || mReportNextDraw) {
        boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
                (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
        if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                updatedConfiguration) {
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
            int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
            //view測量
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
            ......
    }
    ......
    //view佈局
    performLayout(lp, desiredWindowWidth, desiredWindowHeight);
    ......
    //view繪製
    performDraw();
    ......
}
複製程式碼
  • 方法內部分別呼叫了View的measure、layout和draw方法
  • performMeasure方法中需要傳入childWidthMeasureSpec和childHeightMeasureSpec

二、View的measure流程

1、performMeasure

  • DecorView的measure方法
  • DecorView的onMeasure方法
  • DecorView所有子View的measure方法
#ViewRootImpl
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);
    }
}
複製程式碼

2、關於MeasureSpec

(1)定義和作用

  • 每個View都有MeasureSpec,封裝了View的規格和尺寸,其常量代表了32位int值。高2位代表了SpecMode(測量模式),低30位代表SpecSize(測量大小)
  • 作用是在Measure流程中,會將View的LayoutParams根據父控制元件的規則轉換為對應的MeasureSpec,根據MeasureSpec確定View的寬和高
  • MeasureSpec受自身LayoutParams和父容器的MeasureSpec共同影響

(2)SpecMode三種模式:

  • UNSPECIFIED:未指定模式,View想多大就多大,父容器不做限制
  • AT_MOST:最大模式,對應於wrap_comtent屬性,子View的最終大小是父View指定的SpecSize值,並且子View的大小不能大於這個值
  • EXACTLY:精確模式,對應於match_parent屬性和具體的數值,父容器測量出View所需要的大小,也就是SpecSize的值

3、DecorView的MeasureSpec

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

    case ViewGroup.LayoutParams.MATCH_PARENT:
        // Window can't resize. Force root view to be windowSize.
        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;
}
複製程式碼

DecorView的MeasureSpec是由自身的LayoutParams和視窗的尺寸所決定

4、View的measure流程

(1)View的onMeasure方法

#View
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
複製程式碼

通過setMeasuredDimension設定View的寬高

(2)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;
}
複製程式碼
  • wrap_content和match_parent屬性效果一樣

5、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);
        }
    }
}
複製程式碼

遍歷所有子view並對VISIBILITY_MASK不為GONE的view呼叫measureChild()方法

protected void measureChild(View child, int parentWidthMeasureSpec,
        int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();
    //根據父view的MeasureSpec和自身的LayoutParams生成相應的MeasureSpec
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom, lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
複製程式碼

三、View的layout流程

1、performLayout

  • DecorView的layout方法
  • DecorView的onLayout方法
  • DecorView的layoutChildren方法
  • DecorView的所有子View的Layout

(1)View的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);
        ......
    }
}
複製程式碼
  • 根據View相對於父控制元件的左、上、右、下的距離進行佈局
  • 內部呼叫了View的onLayout方法,View和ViewGroup中onLayout為空實現

2、FrameLayout的onLayout方法

@Override
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) {
            ......

            child.layout(childLeft, childTop, childLeft + width, childTop + height);
        }
    }
}
複製程式碼

遍歷所有的子view,並呼叫其layout方法進行佈局

四、View的draw流程

1、performDraw

ViewRootImpl的performDraw; ViewRootImpl的draw; ViewRootImpl的drawSoftware; DecorView(FrameLayout)的draw方法; DecorView(FrameLayout)的dispatchDraw方法; DecorView(FrameLayout)的drawChild方法; DecorView(FrameLayout)的所有子View的draw方法;

2、View的draw流程

public void draw(Canvas canvas) {
    ......
    //(1)繪製背景
    if (!dirtyOpaque) {
        drawBackground(canvas);
    }

    // skip step 2 & 5 if possible (common case)
    final int viewFlags = mViewFlags;
    boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
    boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
    if (!verticalEdges && !horizontalEdges) {
        // 呼叫View的onDraw方法繪製內容
        if (!dirtyOpaque) onDraw(canvas);

        // 繪製子View
        dispatchDraw(canvas);

        drawAutofilledHighlight(canvas);

        // Overlay is part of the content and draws beneath Foreground
        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }

        // 繪製裝飾
        onDrawForeground(canvas);

        // Step 7, draw the default focus highlight
        drawDefaultFocusHighlight(canvas);

        if (debugDraw()) {
            debugDrawFocus(canvas);
        }

        // we're done...
        return;
    }
    ......
}
複製程式碼
  • 繪製View的背景
  • 繪製View的內容
  • 繪製子View
  • 繪製裝飾,比如滾動條

3、ViewGroup的dispatchDraw方法

#ViewGroup
@Override
protected void dispatchDraw(Canvas canvas) {
    ......
    for (int i = 0; i < childrenCount; i++) {
        while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
            final View transientChild = mTransientViews.get(transientIndex);
            if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
                    transientChild.getAnimation() != null) {
                more |= drawChild(canvas, transientChild, drawingTime);
            }
            transientIndex++;
            if (transientIndex >= transientCount) {
                transientIndex = -1;
            }
        }

        final int childIndex = getAndVerifyPreorderedIndex(childrenCount, i, customOrder);
        final View child = getAndVerifyPreorderedView(preorderedList, children, childIndex);
        if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) {
            more |= drawChild(canvas, child, drawingTime);
        }
    }
}

protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    return child.draw(canvas, this, drawingTime);
}
複製程式碼

遍歷所有子View,並呼叫子View的draw方法

相關文章