4源碼的角度分析View

內(nèi)容:View的三大工作流程源碼分析

measure過程

1.View的measure過程

  • 由measure方法來完成,該方法是靜態(tài)的不能被子類重寫,在view的measure中會(huì)調(diào)用onMeasure:
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

setMeasuredDimension方法設(shè)置寬高的測(cè)量值,看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;
    }

EXACTLY情況:getDefaultSize返回的大小就是MeasureSpec中的specSize,這個(gè)specSize就是測(cè)量后的大小。
UNSPECIFIED情況:view的大小為size,即寬高分別為getSuggestedMinimumWidth和getSuggestedMinimumHeight的返回值

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

    }

可以看出,如果view沒有設(shè)置背景,那么view的寬度為mMinWidth,mMinWidth 對(duì)應(yīng)于android:minWidth屬性所指的值,
不指定默認(rèn)為0。如果view指定背景,則view的寬度為max(mMinWidth, mBackground.getMinimumWidth()),看下getMinimumWidth()方法

    public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

getMinimumWidth()返回的就是Drawable的原始寬度,沒有原始寬度則為0,例:ShapeDrawable無原始寬度,BitmapDrawable有。

  • 總結(jié):從getDefaultSize方法中來看,View的寬高由specSize決定。
    結(jié)論:直接繼承View的自定義控件需要重寫onMeasure方法并設(shè)置wrap_content時(shí)的自身大小,否則wrap_content效果為match_parent。
    原因:結(jié)合上述代碼和表4-1理解,上述代碼中可知view在代碼中使用wrap_content,那么specMode是AT_MOST模式,寬高等于
    specSize;差表4-1可知,這種情況specSize是parentSize,而parentSize是父容器中可以使用的大小,match_parent效果一致。
    解決:
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        if ((widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(mWidth,mHeight);
        }else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpaceSize, mHeight);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, heightSpaceSize);
        } else {
        }
    }

在代碼中只需要給view指定一個(gè)默認(rèn)的內(nèi)部寬高(mWidth,mHeight),并在wrap_content時(shí)設(shè)置即可,對(duì)于非wrap_content沿用系統(tǒng)的測(cè)量值即可。(可參考TextView,imageView源碼)

2.ViewGroup的measure過程

  • 對(duì)于ViewGroup除了完成自己的measure過程外,還會(huì)調(diào)用所有子元素的measure方法,各個(gè)子元素再遞歸去執(zhí)行這個(gè)過程。ViewGroup是一個(gè)抽象類,沒有重寫view的onMeasure方法,但提供了measureChildren方法:
 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);
            }
        }
    }

ViewGroup在measure時(shí),會(huì)對(duì)每一個(gè)子元素進(jìn)行measure,measureChild方法:

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

measureChild思想是取出子元素的LayoutParams,然后再通過getChildMeasureSpec來創(chuàng)建子元素的MeasureSpec,接著將MeasureSpec直接傳遞給View的measure方法來進(jìn)行測(cè)量。

  • 下面通過LinearLayout的onMeasure方法來分析ViewGroup的measure過程。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == VERTICAL) {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        }
    }

看下measureVertical方法:由于有300行代碼所以只看核心

 void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
        for (int i = 0; i < count; ++i) {
            final View child = getVirtualChildAt(i);
            measureChildBeforeLayout(child, i, widthMeasureSpec, 0,heightMeasureSpec, usedHeight);
           final int childHeight = child.getMeasuredHeight();
           final int totalLength = mTotalLength;
           mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
                       lp.bottomMargin + getNextLocationOffset(child));
        }
}

系統(tǒng)會(huì)遍歷子元素并對(duì)每個(gè)子元素執(zhí)行measureChildBeforeLayout方法,這個(gè)方法內(nèi)部會(huì)調(diào)用measure方法,各個(gè)元素依次進(jìn)入measure過程,系統(tǒng)會(huì)通過mTotalLength來存儲(chǔ)LinearLayout在豎直方向的初步高度。每測(cè)量一個(gè)子元素mTotalLength都會(huì)增加,增加的部分主要包括了子元素的高度以及子元素在豎直方向上的margin等.當(dāng)子元素測(cè)量完畢后,LinearLayout測(cè)量自己的大?。?/p>

        // Add in our padding
        mTotalLength += mPaddingTop + mPaddingBottom;

        int heightSize = mTotalLength;

        // Check against our minimum height
        heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
        
        // Reconcile our calculated size with the heightMeasureSpec
        int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
        heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
        ···
        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);

對(duì)豎直LinearLayout而言,它在水平方向的測(cè)量過程遵循View的測(cè)量過程,在豎直方向的測(cè)量過程則和view不同。如果它的布局中高度采用的是mathch_parent或者具體數(shù)值,那么它的測(cè)量過程與view一致,即高度為specSize;如果它的布局中高度采用wrap_content,那么它的高度是所有子元素所占的高度總和,但是仍然不能超過父容器的剩余空間,它的最終高度還需要考慮其在豎直方向的padding,看源碼:

       public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
        final int specMode = MeasureSpec.getMode(measureSpec);
        final int specSize = MeasureSpec.getSize(measureSpec);
        final int result;
        switch (specMode) {
            case MeasureSpec.AT_MOST:
                if (specSize < size) {
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
    }

measure完成后,通過getMeasureWidth/Heigth獲取測(cè)量高度。在極端情況下系統(tǒng)多次measure才能確定最終高度,這種情況在onMeasure方法中拿到的測(cè)量寬高不準(zhǔn)確。好的習(xí)慣是在onLayout方法中獲得View的測(cè)量寬高或最終寬高。

  • 一種情況:在Activity已啟動(dòng)的時(shí)候就做一件任務(wù),任務(wù)需要獲取某個(gè)View的寬高。
    View的measure過程和Activity的生命周期方法不是同步執(zhí)行,無法保證Activity執(zhí)行了onCreate、onStart、onResume時(shí)View已經(jīng)測(cè)量完畢,如果View還沒有測(cè)量完畢,那么獲得的寬高就是0。

四種解決辦法:
(1)Activity/View#onWindowFocusChanged
onWindowFocusChanged方法含義:View已經(jīng)初始化完畢,寬高已經(jīng)準(zhǔn)備好了,這時(shí)候獲取寬高沒有問題。注意:當(dāng)Activty繼續(xù)執(zhí)行和暫停執(zhí)行時(shí),onWindowFocusChanged均會(huì)被調(diào)用,如果頻繁的進(jìn)行onResume和onPause,那么onWindowFocusChanged也會(huì)被頻繁的調(diào)用。代碼:

    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
           int width = view.getMeasuredWidth();
           int height = view.getMeasuredHeight();
        }
    }

(2)view.post(runnable)
通過post可以將一個(gè)runnable投遞到消息隊(duì)列尾部,然后等待Looper調(diào)用此runnable的時(shí)候,View也已經(jīng)初始化好了,代碼:

    protected void onStart() {
        super.onStart();
        view.post(new Runnable() {
            @Override
            public void run() {
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
            }
        });
    }

(3)VeiwTreeObserver
使用VeiwTreeObserver的眾多回調(diào)可以完成這個(gè)功能,比如使用
OnGlobalLayoutListener接口,當(dāng)View樹的狀態(tài)發(fā)生改變或者View樹內(nèi)部的View的可見性發(fā)生改變時(shí),onGlobalLayout方法將被回調(diào),此時(shí)獲取View的寬高。注意:伴隨view樹的狀態(tài)改變,onGlobalLayout會(huì)被調(diào)用多次。

 protected void onStart() {
        super.onStart();
        ViewTreeObserver observer = view.getViewTreeObserver();
        observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
            }
        });
    }

(4)view.measure(int widthMeasureSpec, int heightMeasureSpec)
手動(dòng)對(duì)View進(jìn)行measure來得到View的寬高。根據(jù)View的LayoutParams分情況處理:

  • match_parent
    無法measure出具體寬高。
  • 具體的數(shù)值(dp/px)
    比如寬高都是100px:
    private void measureView() {
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }
  • wrap_content
    private void measureView() {
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }

注意:(1 << 30) - 1通過分析MeasureSpec的實(shí)現(xiàn)可以知道,View的尺寸使用30位二進(jìn)制表示,最大是30個(gè)1(即2^30-1),也就是(1 << 30) - 1,在最大化模式下,我們用View理論上能支持的最大值去構(gòu)造MeasureSpec是合理的。

  • 關(guān)于View的measure的錯(cuò)誤用法:原因是違背系統(tǒng)內(nèi)部實(shí)現(xiàn)規(guī)范導(dǎo)致measure過程出錯(cuò),從而結(jié)果不能保證是正確的,錯(cuò)誤代碼:
  private void measureView() {
        int widthMeasureSpec = MeasureSpec.makeMeasureSpec( - 1, MeasureSpec.UNSPECIFIED);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(-1, MeasureSpec.UNSPECIFIED);
        view.measure(widthMeasureSpec, heightMeasureSpec);
    }
 view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

layout過程

作用是ViewGroup用來確定子元素的位置,確定后它在onLayout中遍歷所有子元素并調(diào)用其layout方法,在layout方法中onLayout方法又被調(diào)用。

  • layout方法確定View本身的位置,onLayout確定所有子元素的位置,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);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
    }

首先通過setFrame方法設(shè)定view的四個(gè)頂點(diǎn)的位置,即初始化 mLeft、mTop、mBottom、mRight四值,確定view在父容器中的位置;接著調(diào)用onLayout方法,這個(gè)方法的用途是父容器確定子元素的位置,實(shí)現(xiàn)與具體布局有關(guān),所以View和ViewGroup沒有真正實(shí)現(xiàn)onLayout方法。

  • 看下LinearLayout的onLayout方法:
    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);
        }
    }

layoutVertical部分代碼:

  void layoutVertical(int left, int top, int right, int bottom) {
        ···
        final int count = getVirtualChildCount();
        ···
        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();
               ···
                if (hasDividerBeforeChildAt(i)) {
                    childTop += mDividerHeight;
                }

                childTop += lp.topMargin;
                setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                        childWidth, childHeight);
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

                i += getChildrenSkipCount(child, i);
            }
        }
    }

setChildFrame中的Width和Height實(shí)際上就是子元素的測(cè)量寬高,
此方法會(huì)遍歷所有子元素并調(diào)用setChildFrame方法為子元素指定對(duì)應(yīng)位置,childTop會(huì)逐漸增大,子元素放在靠下位置。
setChildFrame調(diào)用子元素的layout方法,父元素在layout方法中完成自己的定位后,通過onLayout方法調(diào)用子元素的layout方法,子元素又會(huì)通過自己的layout方法來確定自己的位置,這樣一層層傳遞下去就完成了整個(gè)View樹的layout過程。
setChildFrame方法:

   private void setChildFrame(View child, int left, int top, int width, int height) {        
        child.layout(left, top, left + width, top + height);
    }

在layout方法中會(huì)通過setFrame去設(shè)置子元素的四個(gè)頂點(diǎn)的位置,在setFrame中有幾句賦值語句,這樣子元素的位置就確定了

            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
  • 問題:View的測(cè)量寬高與最終寬高的區(qū)別?
    問題具體為:View的getMeasuredWidth和getWidth這兩種方法有什么區(qū)別。
    首先看getWidth和getHeight的方法實(shí)現(xiàn):
    public final int getWidth() {
        return mRight - mLeft;
    }
    public final int getHeight() {
        return mBottom - mTop;
    }

getWidth方法返回的是View的測(cè)量寬度。
答案:在View的默認(rèn)實(shí)現(xiàn)中,View的測(cè)量寬高和最終寬高是相等的,區(qū)別在于測(cè)量寬高形成于View的measure過程,而最終寬高形成于View的layout過程,測(cè)量寬高的賦值時(shí)機(jī)稍微早一些。
在日常開發(fā)中可以認(rèn)為View的測(cè)量寬高等于最終寬高,特殊情況下才會(huì)不同。

draw過程

View的繪制過程遵循如下幾步:

  • 繪制背景background.draw(canvas).
  • 繪制自己(onDraw).
  • 繪制children(dispatchaDraw).
  • 繪制裝飾(onDrawScrollBars)
    源碼:
    public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading
         *      3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        int saveCount;

        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) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

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

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // we're done...
            return;
        }
        ···
    }

View繪制過程的傳遞是通過dispatchDraw來實(shí)現(xiàn),dispatchDraw會(huì)遍歷調(diào)用所有子元素的draw方法,draw事件就一層層傳遞下去??聪耉iew的setWillNotDraw源碼:

    /**
     * If this view doesn't do any drawing on its own, set this flag to
     * allow further optimizations. By default, this flag is not set on
     * View, but could be set on some View subclasses such as ViewGroup.
     *
     * Typically, if you override {@link #onDraw(android.graphics.Canvas)}
     * you should clear this flag.
     *
     * @param willNotDraw whether or not this View draw on its own
     */
    public void setWillNotDraw(boolean willNotDraw) {
        setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
    }

注釋中可以看出,如果一個(gè)view中不需要繪制任何內(nèi)容,那么設(shè)置這個(gè)標(biāo)記位為true以后,系統(tǒng)會(huì)進(jìn)行相應(yīng)的優(yōu)化。
默認(rèn)情況下view沒有啟動(dòng)這個(gè)默認(rèn)標(biāo)記位,但是ViewGroup會(huì)默認(rèn)啟動(dòng)這個(gè)優(yōu)化標(biāo)記位。
實(shí)際開發(fā)的意義:當(dāng)我們的自定義控件繼承ViewGroup并且本身不具備繪制功能時(shí),就可以開啟這個(gè)標(biāo)記位便于系統(tǒng)進(jìn)行后續(xù)的優(yōu)化。當(dāng)明確知道一個(gè)ViewGroup需要通過onDraw來繪制內(nèi)容時(shí),我們需要顯示的關(guān)閉WILL_NOT_DRAW這個(gè)標(biāo)記位。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容