Android 筆記 View 的工作原理 (五)

1、ViewRoot 和DecorView

        ViewRoot 對應於 ViewRootImpl,是連接WindowManager 和DecorView 的紐帶,View 的三大流程均是通過ViewRoot 來完成的。在ActivityThread 中,當Activity 對象被創建完畢後,會將DecorView 添加到 Window 中, 同時創建ViewRootImpl 對象,並將 ViewRootImpl 對象和DecorView 建立關聯,這個過程可參考如下源碼:


root = new ViewRootImpl(view.getContext(),display);
root.setView(view,wparams,panelParentView);

        View 的繪製流程是從 ViewRoot 的 performTraversals 方法開始的,它經過measure(測量)、layout(佈局)、draw(繪製) 三個過程才最終將一個 View 繪製出來,performTraversals 的大致流程如下:


        如圖所示,performTraversals 會依次調用 performMeasure、performLayout、performDraw 三個方法, 這三個方法分別完成頂級 View 的measure、layout、draw三個流程,其中 performMeasure 中會調用 measure 方法,在measure 方法中又會調用 onMeasure 方法,在 onMeasure 方法中會對所有的子元素進行 measure 過程,此時 measure 流程就從父容器傳遞到子元素中了,這樣就完成了一次 measure 過程,接着子元素會重複父容器的 measure 過程,如此反覆就完成了整個View 樹的遍歷。performLayout、performDraw 同理。


MeasureSpec:
MeasureSpec是一個32位的int值,高2位代表模式(SpecMode),低30位代表具體的值(SpecSize),爲了提高並優化效率採用了位與運算。
MeasureSpce 源碼:
    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 {}

        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        public static final int EXACTLY     = 1 << MODE_SHIFT;

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


        public static int makeSafeMeasureSpec(int size, int mode) {
            if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
                return 0;
            }
            return makeMeasureSpec(size, mode);
        }


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


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

        static int adjust(int measureSpec, int delta) {
            final int mode = getMode(measureSpec);
            int size = getSize(measureSpec);
            if (mode == UNSPECIFIED) {
                // No need to adjust size for UNSPECIFIED mode.
                return makeMeasureSpec(size, UNSPECIFIED);
            }
            size += delta;
            if (size < 0) {
                Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
                        ") spec: " + toString(measureSpec) + " delta: " + delta);
                size = 0;
            }
            return makeMeasureSpec(size, mode);
        }

        /**
         * Returns a String representation of the specified measure
         * specification.
         *
         * @param measureSpec the measure specification to convert to a String
         * @return a String with the following format: "MeasureSpec: MODE SIZE"
         */
        public static String toString(int measureSpec) {
            int mode = getMode(measureSpec);
            int size = getSize(measureSpec);

            StringBuilder sb = new StringBuilder("MeasureSpec: ");

            if (mode == UNSPECIFIED)
                sb.append("UNSPECIFIED ");
            else if (mode == EXACTLY)
                sb.append("EXACTLY ");
            else if (mode == AT_MOST)
                sb.append("AT_MOST ");
            else
                sb.append(mode).append(" ");

            sb.append(size);
            return sb.toString();
        }
    }
測量模式(SpecMode)有三種,如下所示:
  • EXACTLY(精確測量): 對應佈局中控件的 layout_width 或 layout_height 屬性指定了具體的數值,指定爲match_parent屬性時的模式。
  • AT_MOST(最大值): 對應佈局中控件的 layout_width 或 layout_height 屬性指定爲wrap_content時。
  • UNSPECIFIED(不確定):不指定View大小測量模式,View可以想多大就多大,這種情況一般用於系統內部,表示測量的狀態。

        View 的默認 onMeasure()方法 只支持 EXACTLY 測量模式,該模式下不用重寫 onMeasure() 方法,即 View 的寬高是精確的,如果是其它模式,則必須重寫 onMeasure() 方法

        重寫onMeaseur() 中會調用父類的 setMeasureDimension(int measuredWidth,int measureHeight)方法,將測量後的寬高設置進去,完成測量的工作。

1、MeasureSpec 和 LayoutParams 的關係:
        LayoutParams 需要和父容器一起才能決定View 的MeasureSpec,從而進一步決定View 的寬高。對於頂級View(即DecorView)和普通View來說,MeasureSpec 的轉換過程略有不同。對於DecorView ,其MeasureSpec 由窗口尺寸和其自身的 LayoutParams 來共同確定;對於普通View 來說,其MeasureSpec 由父容器的 MeasureSpec 和自身的 LayoutParams 來共同決定, MeasureSpec 一旦確定後, onMeasure 中就可以確定 View 的測量寬高。

DecorView:
        在ViewRootImpl 中的 measureHierarchy 方法中的如下代碼展示了 DecorView 的MeasureSpec 的創建過程,其中 desiredWindowWidth、desiredWindowHeight 是屏幕的尺寸

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

接着看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;
    }
由源碼可知,DecorView 的MeasureSpec 的產生過程遵循如下規則,根據它的 LayoutParams 中的寬高的參數來劃分:
  • LayoutParams.MATCH_PARENT:精確模式,大小就是窗口的大小
  • LayoutParams.WRAP_CONTENT:最大模式,大小不定,但不能超過窗口的大小
  • 固定大小(比如100dp):精確模式,大小爲LayoutParams 中指定的大小

    對於普通View 來說,View 的measure過程由 ViewGroup 傳遞而來,先看下ViewGroup 的measureVhildWithMargins 方法:

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

        從上述代碼可知,子元素的MeasureSpec 的創建與父容器的 MeasureSpec 和子元素本身的 LayoutParams 有關,還和View 的 margin及 padding 有關,具體情況可以看一下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);
    }

        上述方法主要是根據父容器的MeasureSpec 同時結合View 自身的 LayoutParams 來確定子元素的 MeasureSpec,參數中 padding 是指父容器中已佔用的空間大小,因此子元素的可用大小爲父容器的尺寸減去 padding,具體代碼如下所示:

        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);
下表是針對 getChildMeasureSpec 的工作原理做的梳理,parentSize 是指父容器中目前可使用的大小

                                             表1 普通View 的 MeasureSpec 的創建規則

     
由表中可知,
  • 如果View 的寬高爲精確值,則其大小爲 LayoutParams 中的大小
  • 如果View 的寬高是 match_parent 時,View 的模式和父容器的模式一致,且其大小爲父容器的剩餘空間
  • 如果View 的寬高是 wrap_content 時,不管父容器爲何種模式,View 都是最大模式,且其大小爲父容器的剩餘空間

View 的工作流程:
        View 的工作流程主要是指measure(測量)、layout(佈局)、draw(繪製) 這三大流程,其中 measure 確定View 的測量寬高,layout 確定 View 的最終寬高和四個頂點的位置,draw 則將 View 繪製到屏幕上。


View 的 measure 過程
        View的 measure 過程由其 measure 方法來完成,measure 方法是一個 final 類型方法,在其中會調用Viw 的onMeasure 方法,onMeasure 方法如下所示:
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

        在onMeasure 方法中,會調用setMeasuredDimension 方法設置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;
    }

        由上可以看出,AT_MOST、EXACTLY 這兩種情況下,getDefaultSize 方法返回的大小就是measureSpec 中的 specSize(就是View 測量後的大小),這裏多次提到測量後的大小,是因爲View 的最終大小是在layout 階段確定的。

        UNSPECIFIED情況一般用於系統內部的測量過程,在這種情況下,View 的大小爲getDefaultSize  的第一個參數,即寬高分別爲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 沒有設置背景,則View 的寬度爲 mMinWidth,而mMinWidth 對應於 android:minWidth 屬性所制定的值,故View 的寬度即爲 android:minWidth 屬性所指定的值。如果這個屬性不指定,則mMinWidth 默認爲0;如果View指定了背景,則 View 的寬度爲 max(mMinWidth, mBackground.getMinimumWidth())中的最大值,getMinimumWidth 的源碼如下:
    public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }
        getMinimumWidth 返回的就是Drawable 的原始寬度,前提是這個Drawable 有原始寬度,否則就返回0。
        Drawable 什麼情況下由原始寬度?比如ShapeDrawable 無原始寬高,而BitmapDrawable 有原始寬高(圖片的尺寸)
 總結:
        從getDefualSize 方法的實現來看,View 的寬高有specSize 決定,結合上述表1 普通View 的 MeasureSpec 的創建規則我們可以得出如下結論:
        直接繼承View 的自定義控件需要重寫 onMeasure 方法,並設置 wrap_content時的View 的自身大小,否則在佈局中使用 wrap_content 就相當於使用 match_parent。
如何解決這個問題,代碼如下:
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);

        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeigth);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth,heightSpecSize);
        } else if (heightSpecMode==MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize,mHeight);
        }
    }
        中mWidth、mHeight 爲View 的默認寬高
ViewGroup 的 measure 過程其
       對於ViewGroup來說,不僅要完成自己的 measure 過程,還要遍歷去調用所有子元素的 measure 方法,各個子元素再遞歸去執行這個過程。和View 不同的是,ViewGroup 是一個抽象類,沒有重寫View 的onMeasure 方法,但提供了一個叫 measureChildern 的方法,如下所示:
    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 時,會對每一個子元素進行 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 構建子元素的 MeasureSpec,最後將獲取的 MeasureSpec 直接傳遞給View 的measure 方法進行測量。

        ViewGroup 並沒有定義其測量的具體過程,這是因爲ViewGroup 是一個抽象類,其測量過程的 onMeasure 方法需要各個子類去具體實現,比如LinearLayout、RelativeLayout等,因爲不同的ViewGroup 子類具有不同的佈局特性,這導致它們的測量細節各不相同,比如LinearLayout 和RelativeLayout 兩者的佈局特性明顯不同,因此ViewGroup 無法統一實現onMeasure 方法。

下面是LinearLayout 的onMeasure 方法來分析ViewGroup 的measure 過程

LinearLayout 的onMeasure 方法:
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == VERTICAL) {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        }
    }

        上述代碼是針對不同佈局的不同測量方法, 我們選豎直佈局的LinearLayout 的測量過程,即measureVertical 方法,如下:

  void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
         ...
        // See how tall everyone is. Also remember max width.
        for (int i = 0; i < count; ++i) {//遍歷測量子元素
            final View child = getVirtualChildAt(i);
            if (child == null) {
                mTotalLength += measureNullChild(i);
                continue;
            }

            if (child.getVisibility() == View.GONE) {//子元素隱藏,跳過
               i += getChildrenSkipCount(child, i);
               continue;
            }

            nonSkippedChildCount++;
            if (hasDividerBeforeChildAt(i)) {//測量子元素之間的間隔
                mTotalLength += mDividerHeight;
            }

            final LayoutParams lp = (LayoutParams) child.getLayoutParams();//獲取子元素的 LayoutParams

            totalWeight += lp.weight;

            final boolean useExcessSpace = lp.height == 0 && lp.weight > 0;
            
            //根據不同的測量模式獲取子元素的高河豎直方向上的 margin
            if (heightMode == MeasureSpec.EXACTLY && useExcessSpace) {
               ...
            }else {
               ...
              measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
              heightMeasureSpec, usedHeight);
               ...
        }

        //測量自己的大小
        // Add in our padding
        mTotalLength += mPaddingTop + mPaddingBottom;

        int heightSize = mTotalLength;

        // Check against our minimum height
        heightSize = Math.max(heightSize, getSuggestedMinimumHeight());

        ...

        maxWidth += mPaddingLeft + mPaddingRight;

        // Check against our minimum width
        maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

        setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
                heightSizeAndState);

        if (matchWidth) {
            forceUniformWidth(count, heightMeasureSpec);
        }
    }
      

        上述代碼中可以看出,首先系統會遍歷子元素並對每個子元素執行measureChildBeforeLayout方法,這個方法內部會調用子元素的measure 方法,這樣各個子元素會依次進入自己的measure過程,系統會通過 mTotalLength 這個變量來存儲 LinearLayout 在豎直方向上的高度,該高度爲子元素的高度和豎直方向上的 margin等,測量完子元素後,LinearLayout 會根據子元素的情況測量自己的大小,同時根據LayoutParams 中佈局模式,獲取不同的高度總和,最終高度還需要考慮豎直方向上的 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);
    }
        View 的measure 過程是三大流程中最複雜的一個,measure 完成以後,通過getMeasureWidth/Height 方法可以正確的獲取到View 的測量寬高。但是在某些極端的情況下,系統可能需要多次measure 才能確定最終的測量寬高,在這種情形下,在onMeasure 方法中拿到的測量寬高很可能是不準確的,建議在onLayout 中去獲取 View 的測量寬高或最終寬高。

場景:比如我們想在Activity 已啓動的時候就做一件任務,這個任務需要獲取到某個View 的寬高。
          因爲View 的measure 過程和 Activity 的生命週期方法不是同步執行的,因此無法保證Activity 執行了 onCreat、onStart、onResume 時某個View 已經測量完畢了,如果View 還沒測量完畢,則獲取的寬高就是0;故在Activity 的onCreat、onStart、onResume中無法正確的獲取到View 的寬高,但可通過以下四種方法解決這個問題:

1)、Activity/View#onWindowFocusChange
        onWindowFocusChange 含義:View 已經初始化完畢,寬高已經準備好了,此時去獲取View 的寬高是沒問題的。但需注意,onWindowFocusChange 會被調用多次,當Activity 的窗口得到焦點和失去焦點時均會被調用一次。即當Activity 頻繁的進行onResume 和 onPause時,onWindowFocusChange也會被頻繁的調用,典型代碼如下:
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
          int width = view.getMeasuredWidth();
          int height = view.getMeasuredHeight();
        }
    }

2)、view.post(runnable)
        通過 post 可以講一個runnable 投遞到消息隊列的尾部,然後等待 Looper 調用此 runnable 的時候,View 也已經初始化好了,典型代碼如下:
    @Override
    protected void onStart() {
        super.onStart();
        view.post(new Runnable() {
            @Override
            public void run() {
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
            }
        });
    }



3)、ViewTreeObserver
        使用 ViewTreeObserver 的總舵回調可以完成這個功能,比如使用 addOnGlobalLayoutListener 這個家口,當View 樹的狀態發生改變或者 View 樹內部的View 可見性發生改變時,onGlobalLayout方法會被回調,因此這是獲取 View 的寬高一個很好的時機。但需注意,伴隨着View 樹的狀態改變等,onGlobalLayout 會被多次調用。典型代碼如下所示:
    @Override
    protected void onStart() {
        super.onStart();
        ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
            }
        });
    }


4)、view.measure(int widthMeasureSpec, int heightMeasureSpec)
        通過手動對View 進行measure 來得到 View 的寬高,這種方法比較複雜,需要根據View 的LayoutParams 來分情況處理:
        match_parent
            直接放棄,無法measure 出具體的寬高,因爲根據View 的measure 過程,如上表1 所述,構造此種MeasureSpec 需要知道 parentSize,即父容器的剩餘空間,而這時我們無法知道parentSize 的大小,所以理論上不可能測量出 View 的大小。
        
        具體的數值(dp/px)
            比如寬高都是100 px,如下measure:
        int widthMeasureSpec  = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
        int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
        view.measure(widthMeasureSpec, heightMeasureSpec);

  wrap_content
            如下 measure:
        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 是View的尺寸使用30位二進制表示,即最大值就是(1<<30)-1,在最大化模式下,我們使用理論上View能支持的最大值去構造MeasureSpec是合理的。

layout 過程:
        Layout 的作用是ViewGroup 用來確定子元素位置的,當 ViewGroup 的位置被確定爲後,在它的onLayout 中會遍歷所有的子元素並調用它們的 拉有方法,在layout 方法中又會調用自己的 onLayout方法,最終確定自身的位置,View 的layout 方法如下所示:

    @SuppressWarnings({"unchecked"})
    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;
        //setFrame(l, t, r, b) 方法設定 View 的四個頂點
        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);//調用 onLayout 方法

            if (shouldDrawRoundScrollbar()) {
                if(mRoundScrollbarRenderer == null) {
                    mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
                }
            } else {
                mRoundScrollbarRenderer = null;
            }

            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;

        if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
            mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
            notifyEnterOrExitForAutoFillIfNeeded(true);
        }
    }

        layout 方法的大致流程如下:首先會通過 setFrame 方法來設置View 的四個頂點的位置,即初始化  mLeft 、mTop、mRight 、mBottom;
View 的四個頂點位置確定後,View 在父容器中的位置也就確定了。接着會調用onLayout 方法,這個方法的用途是父容器確定子元素的位置,它是一個抽象方法,它的具體實現和具體的佈局有關。
        setFrame 源碼:
 protected boolean setFrame(int left, int top, int right, int bottom) {
        boolean changed = false;

        if (DBG) {
            Log.d("View", this + " View.setFrame(" + left + "," + top + ","
                    + right + "," + bottom + ")");
        }

        if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
            changed = true;

            // Remember our drawn bit
            int drawn = mPrivateFlags & PFLAG_DRAWN;

            int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

            // Invalidate our old position
            invalidate(sizeChanged);
            //初始化賦值
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

            mPrivateFlags |= PFLAG_HAS_BOUNDS;


            if (sizeChanged) {
                sizeChange(newWidth, newHeight, oldWidth, oldHeight);
            }

            if ((mViewFlags & VISIBILITY_MASK) == VISIBLE || mGhostView != null) {
                // If we are visible, force the DRAWN bit to on so that
                // this invalidate will go through (at least to our parent).
                // This is because someone may have invalidated this view
                // before this call to setFrame came in, thereby clearing
                // the DRAWN bit.
                mPrivateFlags |= PFLAG_DRAWN;
                invalidate(sizeChanged);
                // parent display list may need to be recreated based on a change in the bounds
                // of any child
                invalidateParentCaches();
            }

            // Reset drawn bit to original value (invalidate turns it off)
            mPrivateFlags |= drawn;

            mBackgroundSizeChanged = true;
            mDefaultFocusHighlightSizeChanged = true;
            if (mForegroundInfo != null) {
                mForegroundInfo.mBoundsChanged = true;
            }

            notifySubtreeAccessibilityStateChangedIfNeeded();
        }
        return changed;
    }

        下面是LinearLayout 的 onLayout 方法:
    @Override
    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 paddingLeft = mPaddingLeft;

        int childTop;
        int childLeft;

        // Where right end of child should go
        final int width = right - left;
        int childRight = width - mPaddingRight;

        // Space available for child
        int childSpace = width - paddingLeft - mPaddingRight;

        final int count = getVirtualChildCount();

        final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
        final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;

        switch (majorGravity) {
           case Gravity.BOTTOM:
               // mTotalLength contains the padding already
               childTop = mPaddingTop + bottom - top - mTotalLength;
               break;

               // mTotalLength contains the padding already
           case Gravity.CENTER_VERTICAL:
               childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
               break;

           case Gravity.TOP:
           default:
               childTop = mPaddingTop;
               break;
        }
        //遍歷子元素
        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();
                //獲取子元素的 LayoutParams
                final LinearLayout.LayoutParams lp =
                        (LinearLayout.LayoutParams) child.getLayoutParams();

                int gravity = lp.gravity;
                if (gravity < 0) {
                    gravity = minorGravity;
                }
                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = paddingLeft + ((childSpace - childWidth) / 2)
                                + lp.leftMargin - lp.rightMargin;
                        break;

                    case Gravity.RIGHT:
                        childLeft = childRight - childWidth - lp.rightMargin;
                        break;

                    case Gravity.LEFT:
                    default:
                        childLeft = paddingLeft + lp.leftMargin;
                        break;
                }

                if (hasDividerBeforeChildAt(i)) {
                    childTop += mDividerHeight;
                }
                
                childTop += lp.topMargin;
                //設置子元素的位置,內部會調用子元素的layou 方法
                setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                        childWidth, childHeight);
                
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

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

        從上述代碼中可看出,layoutVertical 首先會遍歷所有子元素並調用setChildFrame 方法來爲子元素指定位置,其中 childTop 會逐漸增大,意味着後面的子元素會被放置在靠下的位置,剛好符合豎直方向的LinearLayout 特性,同時setChildFrame 方法內部會調用子元素的 layout 方法,由前面可知,layout 方法會調用內部的 onLayout 方法來確定自己的位置,就這樣一層層傳遞下去完成整個Viw 樹的 layou過程。

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

getWidth/getHeight 源碼:

 @ViewDebug.ExportedProperty(category = "layout")
    public final int getWidth() {
        return mRight - mLeft;
    }

    /**
     * Return the height of your view.
     *
     * @return The height of your view, in pixels.
     */
    @ViewDebug.ExportedProperty(category = "layout")
    public final int getHeight() {
        return mBottom - mTop;
    }

        從源碼我們可以得知,getWidth/getHeight 獲取的值就是View 的測量寬高,但在某些情況下我們可以改變getWidth/getHeight  的返回值,如下所示:

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right+100, bottom+100);
    }
        這樣我們通過getWidth/getHeight 獲取的View 的寬高和View 測量的寬高就會不一致

Tip:getMeasuredWidth/getMeasuredHeight 和 getWidth/getHeight 的區別?
        getMeasuredWidth/getMeasuredHeight 在View 的 measure 流程中被賦值,getWidth/getHeight 在View 的layout 流程中被賦值,默認情況下兩者的值相等,但在 layout 流程中可以改變View 的最終 寬高,


draw 過程
        draw過程的作用是將View 繪製到屏幕上,View 的繪製過程遵循如下幾步:
  1. 繪製背景 background.draw(canvas)
  2. 會致自己 onDraw
  3. 繪製 children(dispatchDraw)
  4. 繪製裝飾(onDrawForeground(canvas))
        這一點從draw 的源碼可以看出,源碼如下:

    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);//繪製子元素

            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);//繪製裝飾

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

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

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

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

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

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

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

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

        View 的繪製過程的傳遞是通過 dispatchDraw 來實現的,dispatchDraw 會遍歷所有子元素的 draw 方法,如此 draw 事件就一層一層的傳遞下去。

        View 有一個特殊的方法,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);
    }


        這個方法表示,如果一個View 不需要繪製任何內容,那麼設置這個標記位爲 true 後,系統會進行相應的優化。默認情況下,View 沒有啓用這個優化標記位,但是ViewGroup 會默認啓用這個優化標記位。
        這個標記位對實際開發的意義是:當我們的自定義控件繼承於 ViewGroup 並且本身不具備繪製功能時,就可以開啓這個標記位從而便於系統進行後續的優化。當明確知道一個ViewGroup 需要通過onDraw 來繪製內容時,我們需要顯示地關閉 WILL_NOT_DRAW 這個標記位。

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