Androiod中View的工作原理


個人博客:http://zhangsunyucong.top

前言

這篇文章主要講解view的工作原理中的三大流程,包括測量流程,佈局流程,繪製流程。這些都是自定義控件的基礎。下面先對三大流程的職責做簡要的概述:

測量流程確定了控件的測量的大小;
佈局流程確定了控件在父控件中的四個位置的座標和控件的實際大小;
繪製流程負責控件的繪製並顯示在屏幕上。

view的繪製流程是從哪裏開始的?

View的繪製流程是從ViewRoot的performTraversals開始的。在performTraversals經過一堆的邏輯,會分別調用performMeasure,performLayout,performDraw。
然後在view樹中,先後調用一下的方法:

performMeasure,measure onMeasure
performLayout,layout, onLayout
performDraw, draw, onDraw, dispatchDraw(繪製子view)

ViewRoot的實現類是ViewRootImpl,在ActivityThread中創建。

MeasureSpec

MeasureSpec是view的測量規格,是一個int數值。在java中的int是32位的,所以MeasureSpec可以利用32位的一個數值來表示view的大少size和規格mode。在ViewRootImpl.java中提供了MeasureSpec組合和分解的方法。MeasureSpec是ViewRootImpl.java中的一個公開靜態內部類,源碼如下:

ViewRootImpl#MeasureSpec

    public static class MeasureSpec {
        private static final int MODE_SHIFT = 30;
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        /** @hide */
        @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
        @Retention(RetentionPolicy.SOURCE)
        public @interface MeasureSpecMode {}

        /**
         * Measure specification mode: The parent has not imposed any constraint
         * on the child. It can be whatever size it wants.
         */
        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        /**
         * Measure specification mode: The parent has determined an exact size
         * for the child. The child is going to be given those bounds regardless
         * of how big it wants to be.
         */
        public static final int EXACTLY     = 1 << MODE_SHIFT;

        /**
         * Measure specification mode: The child can be as large as it wants up
         * to the specified size.
         */
        public static final int AT_MOST     = 2 << MODE_SHIFT;

        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                          @MeasureSpecMode int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

        ...

        @MeasureSpecMode
        public static int getMode(int measureSpec) {
            //noinspection ResourceType
            return (measureSpec & MODE_MASK);
        }

        public static int getSize(int measureSpec) {
            return (measureSpec & ~MODE_MASK);
        }
        ...
    }

在上面,MODE_SHIFT爲什麼是30?因爲它是使用高2位表示mode,低30爲表示size。
MODE_MASK爲0x3,二進制表示是

0000 0000 0000 0000 0000 0000 0000 0011

它左移30位後爲

1100 0000 0000 0000 0000 0000 0000 0000

由MODE_MASK理解組合makeMeasureSpec中的(size & ~MODE_MASK) | (mode & MODE_MASK)

size & ~MODE_MASK,就是

size & ~MODE_MASK = size & 0011 1111 1111 1111 1111 1111 1111 1111size=32時,
100000 & ~MODE_MASK = 100000 & 0011 1111 1111 1111 1111 1111 1111 1111 = 0000 0000 0000 0000 0000 0000 0010 0000 = 32

同理可知mode

最後做與運算,將它們相加

從源碼中可以看出,mode有UNSPECIFIED,EXACTLY,AT_MOST。其中UNSPECIFIED等於0,AT_MOST是小於0,EXACTLY等於0。

MeasureSpec的創建和測量流程

MeasureSpec是由父容器的約束和佈局參數LayoutParams共同決定的。它在DecorView和普通view中創建也是不一樣的。DecorView的父容器是Window,所以DecorView的MeasureSpec由窗口大小和佈局參數共同決定的。普通view是由父容器的MeasureSpec和佈局參數共同決定的。

(1)在DecorView中

ViewRootImpl#measureHierarchy

childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);

ViewRootImpl#getRootMeasureSpec
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;
    }

當view設置MATCH_PARENT時,measureSpec的mode是MeasureSpec.EXACTLY,size是windowSize窗口大小。
當view設置WRAP_CONTENT時,measureSpec的mode是MeasureSpec.AT_MOST,size是windowSize窗口大小。
當view設置具體大小時,measureSpec的mode是MeasureSpec.EXACTLY,size是view設置的具體大小。

(2)在普通view中

ViewGroup#measureChildWithMargins

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

在ViewGroup#getChildMeasureSpec

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

在getChildMeasureSpec中列出了在父容器MeasureSpec和view的佈局參數下創建MeasureSpec的各種情況。得到MeasureSpec後,在measureChildWithMargins中將它傳遞給child的measure方法。在measure方法再傳給onMeasure方法。這就是onMeasure方法中兩個參數的來源。

View#onMeasure

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

View#setMeasuredDimension中會調用setMeasuredDimensionRaw方法
View#setMeasuredDimensionRaw

private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth;
        mMeasuredHeight = measuredHeight;

        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
    }

到這裏就已經確定的view測量的大小。通過getMeasuredWidth()和getMeasuredHeight()就可以得到它們的值。

View#getSuggestedMinimumWidth

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

這裏是說,控件是否設置了背景和最小大小。對應於android:background和android:minWidth。

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

UNSPECIFIED據說一般是用於表示內部正處於測量的狀態。在普通view中我們只要關注AT_MOST和EXACTLY。當view設置match_parent和具體大小時,是EXACTLY,wrap_content時是AT_MOST。爲什麼會是這樣?可以看getChildMeasureSpec方法中各種情況。

所以當我們自定義view時,如果不處理AT_MOST情況,即wrap_content時,控件的大少就是父控件的大小。EXACTLY是可以正常被getDefaultSize處理的。

在ViewGroup中是沒有重寫onMeasure方法的,因爲ViewGroup的大小還與ViewGroup的具體的佈局特性有關。如LinearLayout和RelativeLayout的onMeasure不一樣的。所以自定義ViewGroup時,要重寫onMeasure方法。

但是,ViewGroup提供了測量子view的方法的,measureChildren和measureChildWithMargins,measureChild。

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

ViewGroup#measureChildWithMargins

protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                        + widthUsed, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                        + heightUsed, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }

measureChild在measureChildren被循環遍歷子view時調用。measureChildren和measureChildWithMargins的區別是,measureChildren是減去父控件的padding,而measureChildWithMargins減去了父控件的padding和view的margin。這直接影響了測量的大小是否包含了padding和margin。也就是view可以設置的最大大小是減去父控件的padding和view的內邊距。

綜上所述,在view中,就可以確定view的大小,提供了默認的onMeasure方法,但是默認的onMeasure方法不能正確處理AT_MOST(Wrap_content)的情況。在ViewGroup中,因爲ViewGroup的具體大小和ViewGroup的佈局特性有關,自定義ViewGroup要重寫該方法。

佈局流程

View#layout

    public void layout(int l, int t, int r, int b) {
        ...

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

            ...
        }

        ...
    }

在layout中分別調用了setFrame或者setOpticalFrame和onLayout。

setFrame或者setOpticalFrame中,賦值給mLeft,mTop,mRight,mBottom,確定了view的四個頂點,通過它們的get方法可以得到相應的值。這就確定了view在父控件中的位置座標和view的寬和高。

View#onLayout是一個空實現。因爲view只需要確定自己在父控件的位置即可。onLayout是用於在ViewGroup中確定子view的位置的。而onLayout的實現同樣是與具體的ViewGroup的佈局特性有關的。需要在自定義ViewGroup實現。

繪製流程

public void draw(Canvas canvas) {
       ...

        /*
         * 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);

            drawAutofilledHighlight(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);
            ...
        }  
        ...
    }    

draw過程就是主要就是,上面源碼所說的那幾個步驟。

1、如果需要背景,繪製背景
2、onDraw中,繪製自身
3、dispatchDraw中,繪製子view
4、onDrawForeground中繪製裝飾

在自定義ViewGroup時,可以在dispatchDraw中遍歷子view進行繪製。

實例

佈局

<?xml version="1.0" encoding="utf-8"?>
<com.example.hyj.ht_test.widget.custom.CustomViewGroup
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <com.example.hyj.ht_test.widget.custom.CustomViewGroup1
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_height="wrap_content">

       <com.example.hyj.ht_test.widget.custom.CustomView
           android:id="@+id/btn"
           android:background="@color/common_color"
           android:layout_margin="10dp"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"/>


    </com.example.hyj.ht_test.widget.custom.CustomViewGroup1>

</com.example.hyj.ht_test.widget.custom.CustomViewGroup>

CustomViewGroup1

public class CustomViewGroup1 extends ViewGroup {

    private Context mContext;

    private static final String TAG = "CustomViewGroup";

    ....構造函數...

    public static class CustomLayoutParams extends MarginLayoutParams {

        public CustomLayoutParams(MarginLayoutParams source) {
            super(source);
        }

        public CustomLayoutParams(android.view.ViewGroup.LayoutParams source) {
            super(source);
        }

        public CustomLayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);
        }

        public CustomLayoutParams(int width, int height) {
            super(width, height);
        }
    }

    /**
     * 生成默認的佈局參數
     */
    @Override
    protected CustomLayoutParams generateDefaultLayoutParams() {
        return new CustomLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    /**
     * 生成佈局參數
     * 將佈局參數包裝成我們的
     */
    @Override
    protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {
        return new CustomLayoutParams(p);
    }

    /**
     * 生成佈局參數
     * 從屬性配置中生成我們的佈局參數
     */
    @Override
    public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new CustomLayoutParams(getContext(), attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //measureChildren(widthMeasureSpec, heightMeasureSpec);

        int parentWidth = 0;
        int parentHeight = 0;
        int childCount = getChildCount();
        if(childCount > 0) {
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                measureChildWithMargins(child, widthMeasureSpec, 0,
                        heightMeasureSpec, 0);
                CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();
                if (child.getVisibility() != View.GONE) {
                    parentWidth = getPaddingLeft() + getPaddingRight() +
                            child.getMeasuredWidth() + clp.leftMargin + clp.rightMargin ;
                    parentHeight = getPaddingTop() + getPaddingBottom() +
                            child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;
                }
            }
        }
        setMeasuredDimension(parentWidth, parentHeight);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

        int childCount = getChildCount();
        int paddingTop = 0;
        if(childCount > 0) {
            for(int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                if(child.getVisibility() != View.GONE) {
                    int measuredHeight = child.getMeasuredHeight();
                    int measuredWidth = child.getMeasuredWidth();
                    CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();
                    paddingTop = paddingTop + child.getPaddingTop();
                    child.layout(getPaddingLeft() + clp.leftMargin,
                            getPaddingTop() + clp.topMargin,
                            getPaddingLeft() + clp.leftMargin + measuredWidth,
                            getPaddingTop() + clp.leftMargin + measuredHeight);
                }
            }
        }
    }


}

CustomViewGroup是默認的實現可以

public class CustomView extends View {

    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getSize(600, widthMeasureSpec),
                getSize(600, heightMeasureSpec));
    }

    private int getSize(int size, int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        if(specMode != MeasureSpec.EXACTLY) {
            result = size;
        } else {
            result = specSize;
        }
        return result;
    }

}

其實這些代碼是《Android的MotionEvent事件分發機制》中用的代碼基礎上加的.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章