【朝花夕拾】Android自定義View篇之(一)View繪製流程

前言html

       轉載請申明轉自【http://www.javashuo.com/article/p-wilmsuvq-g.html】謝謝!java

       自定義View、多線程、網絡,被認爲是Android開發者必須牢固掌握的最基礎的三大基本功。Android View的繪製流程原理又是學好自定義View的理論基礎,因此掌握好View的繪製原理是Android開發進階中沒法繞過的一道坎。而關乎到原理性的東西每每又讓不少初學者感到難如下手,因此真正掌握的人並很少。本文采用很是淺顯的語言,從順着Android源碼的思路,對View的整個繪製流程進行近乎「地毯式搜索」般的方式,對其中的關鍵流程和知識點進行查證和分析,以圖讓初級程序員都能輕鬆讀懂。本文最大的特色,就是最大限度地向源碼要答案,從源碼中追流程的前因後果,在註釋中查功能的點點滴滴,全部的結論都儘可能在源碼和註釋中找根據。android

       爲了能對其中的重難點分析透徹,文中貼出了大量的源碼依據以及源碼中的註釋,並對重要的註釋進行了翻譯和講解,因此文章會比較長。講解該知識點的文章廣泛都很是長,因此但願讀者可以秉承程序員吃苦耐勞的精神,攻克這個難關。本文中的源碼是基於API26的,即Android8.0系統版本,主要內容大體以下:程序員

 

 

1、View繪製的三個流程編程

       咱們知道,在自定義View的時候通常須要重寫父類的onMeasure()、onLayout()、onDraw()三個方法,來完成視圖的展現過程。固然,這三個暴露給開發者重寫的方法只不過是整個繪製流程的冰山一角,更多複雜的幕後工做,都讓系統給代勞了。一個完整的繪製流程包括measure、layout、draw三個步驟,其中:canvas

     measure:測量。系統會先根據xml佈局文件和代碼中對控件屬性的設置,來獲取或者計算出每一個View和ViewGrop的尺寸,並將這些尺寸保存下來。c#

     layout:佈局。根據測量出的結果以及對應的參數,來肯定每個控件應該顯示的位置。api

     draw:繪製。肯定好位置後,就將這些控件繪製到屏幕上。網絡

 

2、Android視圖層次結構簡介  多線程

       在介紹View繪製流程以前,我們先簡單介紹一下Android視圖層次結構以及DecorView,由於View的繪製流程的入口和DecorView有着密切的聯繫。

 

       我們平時看到的視圖,其實存在如上的嵌套關係。上圖是針對比較老的Android系統版本中製做的,新的版本中會略有出入,還有一個狀態欄,但總體上沒變。咱們平時在Activity中setContentView(...)中對應的layout內容,對應的是上圖中ViewGrop的樹狀結構,實際上添加到系統中時,會再裹上一層FrameLayout,就是上圖中最裏面的淺藍色部分了。

       這裏我們再經過一個實例來繼續查看。AndroidStudio工具中提供了一個佈局視察器工具,經過Tools > Android > Layout Inspector能夠查看具體某個Activity的佈局狀況。下圖中,左邊樹狀結構對應了右邊的可視圖,可見DecorView是整個界面的根視圖,對應右邊的紅色框,是整個屏幕的大小。黃色邊框爲狀態欄部分;那個綠色邊框中有兩個部分,一個是白框中的ActionBar,對應了上圖中紫色部分的TitleActionBar部分,即標題欄,平時我們能夠在Activity中將其隱藏掉;另一個藍色邊框部分,對應上圖中最裏面的藍色部分,即ContentView部分。下圖中左邊有兩個藍色框,上面那個中有個「contain_layout」,這個就是Activity中setContentView中設置的layout.xml佈局文件中的最外層父佈局,我們能經過layout佈局文件直接徹底操控的也就是這一塊,當其被add到視圖系統中時,會被系統裹上ContentFrameLayout(顯然是FrameLayout的子類),這也就是爲何添加layout.xml視圖的方法叫setContentView(...)而不叫setView(...)的緣由。

 

 

3、故事開始的地方

        若是對Activity的啓動流程有必定了解的話,應該知道這個啓動過程會在ActivityThread.java類中完成,在啓動Activity的過程當中,會調用到handleResumeActivity(...)方法,關於視圖的繪製過程最初就是從這個方法開始的。

 

  一、View繪製起源UML時序圖

       整個調用鏈以下圖所示,直到ViewRootImpl類中的performTraversals()中,才正式開始繪製流程了,因此通常都是以該方法做爲正式繪製的源頭。

圖3.1 View繪製起源UML時序圖

 

   二、handleResumeActivity()方法

       在這我們先大體看看ActivityThread類中的handleResumeActivity方法,我們這裏只貼出關鍵代碼:

 1 //===========ActivityThread.java==========
 2 final void handleResumeActivity(...) {
 3     ......
 4     //跟蹤代碼後發現其初始賦值爲mWindow = new PhoneWindow(this, window, activityConfigCallback);
 5     r.window = r.activity.getWindow(); 
 6        //從PhoneWindow實例中獲取DecorView  
 7     View decor = r.window.getDecorView();
 8     ......
 9     //跟蹤代碼後發現,vm值爲上述PhoneWindow實例中獲取的WindowManager。
10     ViewManager wm = a.getWindowManager();
11     ......
12     //當前window的屬性,從代碼跟蹤來看是PhoneWindow窗口的屬性
13     WindowManager.LayoutParams l = r.window.getAttributes();
14     ......
15     wm.addView(decor, l);
16     ......
17 }

       上述代碼第8行中,ViewManager是一個接口,addView是其中定義個一個空方法,WindowManager是其子類,WindowManagerImpl是WindowManager的實現類(順便囉嗦一句,這種方式叫作面向接口編程,在父類中定義,在子類中實現,在Java中很常見)。第4行代碼中的r.window的值能夠根據Activity.java的以下代碼得知,其值爲PhoneWindow實例。

 1 //===============Activity.java=============
 2 private Window mWindow;
 3 public Window getWindow() {
 4    return mWindow;
 5 }
 6 
 7 final void attach(...){
 8    ......
 9    mWindow = new PhoneWindow(this, window, activityConfigCallback);
10    ......
11 }

 

三、兩個重要參數分析

       之因此要在這裏特地分析handleResumeActivity()方法,除了由於它是整個繪製流程的最初源頭外,還有就是addView的兩個參數比較重要,它們通過一層一層傳遞後進入到ViewRootImpl中,在後面分析繪製中要用到。這裏再看看這兩個參數的相關信息:

    (1)參數decor

 1 //==========PhoneWindow.java===========
 2 // This is the top-level view of the window, containing the window decor.
 3 private DecorView mDecor;
 4 ......
 5 public PhoneWindow(...){
 6    ......
 7    mDecor = (DecorView) preservedWindow.getDecorView();
 8    ......
 9 }
10 
11 @Override
12 public final View getDecorView() {
13    ......
14    return mDecor;
15 }

可見decor參數表示的是DecorView實例。註釋中也有說明:這是window的頂級視圖,包含了window的decor。

    (2)參數l

 1 //===================Window.java===================
 2 //The current window attributes.
 3     private final WindowManager.LayoutParams mWindowAttributes =
 4         new WindowManager.LayoutParams();
 5 ......
 6 public final WindowManager.LayoutParams getAttributes() {
 7         return mWindowAttributes;
 8     }
 9 ......
10 
11 
12 //==========WindowManager.java的內部類LayoutParams extends ViewGroup.LayoutParams=============
13 public LayoutParams() {
14             super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
15             ......
16         }
17 
18 
19 //==============ViewGroup.java內部類LayoutParams====================
20 public LayoutParams(int width, int height) {
21             this.width = width;
22             this.height = height;
23         }

該參數表示l的是PhoneWindow的LayoutParams屬性,其width和height值均爲LayoutParams.MATCH_PARENT。

 

        在源碼中,WindowPhone和DecorView經過組合方式聯繫在一塊兒的,而DecorView是整個View體系的根View。在前面handleResumeActivity(...)方法代碼片斷中,當Actiivity啓動後,就經過第14行的addView方法,來間接調用ViewRootImpl類中的performTraversals(),從而實現視圖的繪製。

 

4、主角登場 

   無疑,performTraversals()方法是整個過程的主角,它把控着整個繪製的流程。該方法的源碼有大約800行,這裏我們僅貼出關鍵的流程代碼,以下所示:
 1 // =====================ViewRootImpl.java=================
 2 private void performTraversals() {
 3    ......
 4    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
 5    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);      
 6    ......
 7    // Ask host how big it wants to be
 8    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
 9    ......
10    performLayout(lp, mWidth, mHeight);
11    ......
12    performDraw();
13 }

 上述代碼中就是一個完成的繪製流程,對應上了第一節中提到的三個步驟:

      1)performMeasure():從根節點向下遍歷View樹,完成全部ViewGroup和View的測量工做,計算出全部ViewGroup和View顯示出來須要的高度和寬度;

      2)performLayout():從根節點向下遍歷View樹,完成全部ViewGroup和View的佈局計算工做,根據測量出來的寬高及自身屬性,計算出全部ViewGroup和View顯示在屏幕上的區域;

      3)performDraw():從根節點向下遍歷View樹,完成全部ViewGroup和View的繪製工做,根據佈局過程計算出的顯示區域,將全部View的當前需顯示的內容畫到屏幕上。

我們後續就是經過對這三個方法來展開研究整個繪製過程。

 

5、measure過程分析

       這三個繪製流程中,measure是最複雜的,這裏會花較長的篇幅來分析它。本節會先介紹整個流程中很重要的兩個類MeasureSpec和ViewGroup.LayoutParams類,而後介紹ViewRootImpl、View及ViewGroup中測量流程涉及到的重要方法,最後簡單梳理DecorView測量的整個流程並連接一個測量實例分析整個測量過程。

 

  一、MeasureSpec簡介

       這裏我們直接上源碼吧,先直接經過源碼和註釋認識一下它,若是看不懂也不要緊,在後面使用的時候再回頭來看看。

 1 /**
 2      * A MeasureSpec encapsulates the layout requirements passed from parent to child.
 3      * Each MeasureSpec represents a requirement for either the width or the height.
 4      * A MeasureSpec is comprised of a size and a mode. There are three possible
 5      * modes:
 6      * <dl>
 7      * <dt>UNSPECIFIED</dt>
 8      * <dd>
 9      * The parent has not imposed any constraint on the child. It can be whatever size
10      * it wants.
11      * </dd>
12      *
13      * <dt>EXACTLY</dt>
14      * <dd>
15      * The parent has determined an exact size for the child. The child is going to be
16      * given those bounds regardless of how big it wants to be.
17      * </dd>
18      *
19      * <dt>AT_MOST</dt>
20      * <dd>
21      * The child can be as large as it wants up to the specified size.
22      * </dd>
23      * </dl>
24      *
25      * MeasureSpecs are implemented as ints to reduce object allocation. This class
26      * is provided to pack and unpack the &lt;size, mode&gt; tuple into the int.
27      */
28     public static class MeasureSpec {
29         private static final int MODE_SHIFT = 30;
30         private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
31         ......
32         /**
33          * Measure specification mode: The parent has not imposed any constraint
34          * on the child. It can be whatever size it wants.
35          */
36         public static final int UNSPECIFIED = 0 << MODE_SHIFT;
37 
38         /**
39          * Measure specification mode: The parent has determined an exact size
40          * for the child. The child is going to be given those bounds regardless
41          * of how big it wants to be.
42          */
43         public static final int EXACTLY     = 1 << MODE_SHIFT;
44 
45         /**
46          * Measure specification mode: The child can be as large as it wants up
47          * to the specified size.
48          */
49         public static final int AT_MOST     = 2 << MODE_SHIFT;
50         ......
51        /**
52          * Creates a measure specification based on the supplied size and mode.
53          *...... 
54          *@return the measure specification based on size and mode        
55          */
56         public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
57                                           @MeasureSpecMode int mode) {
58             if (sUseBrokenMakeMeasureSpec) {
59                 return size + mode;
60             } else {
61                 return (size & ~MODE_MASK) | (mode & MODE_MASK);
62             }
63             ......
64             
65         }
66         ......
67         /**
68          * Extracts the mode from the supplied measure specification.
69          *......
70          */
71         @MeasureSpecMode
72         public static int getMode(int measureSpec) {
73             //noinspection ResourceType
74             return (measureSpec & MODE_MASK);
75         }
76 
77         /**
78          * Extracts the size from the supplied measure specification.
79          *......
80          * @return the size in pixels defined in the supplied measure specification
81          */
82         public static int getSize(int measureSpec) {
83             return (measureSpec & ~MODE_MASK);
84         }
85         ......
86 }

 從這段代碼中,我們能夠獲得以下的信息:

    1)MeasureSpec歸納了從父佈局傳遞給子view佈局要求。每個MeasureSpec表明了寬度或者高度要求,它由size(尺寸)和mode(模式)組成。

    2)有三種可能的mode:UNSPECIFIED、EXACTLY、AT_MOST

    3)UNSPECIFIED:未指定尺寸模式。父佈局沒有對子view強加任何限制。它能夠是任意想要的尺寸。(筆者注:這個在工做中極少碰到,聽說通常在系統中才會用到,後續會講得不多)

    4)EXACTLY:精確值模式。父佈局決定了子view的準確尺寸。子view不管想設置多大的值,都將限定在那個邊界內。(筆者注:也就是layout_width屬性和layout_height屬性爲具體的數值,如50dp,或者設置爲match_parent,設置爲match_parent時也就明確爲和父佈局有一樣的尺寸,因此這裏不要覺得筆者搞錯了。當明確爲精確的尺寸後,其也就被給定了一個精確的邊界)

    5)AT_MOST:最大值模式。子view能夠一直大到指定的值。(筆者注:也就是其寬高屬性設置爲wrap_content,那麼它的最大值也不會超過父佈局給定的值,因此稱爲最大值模式)

    6)MeasureSpec被實現爲int型來減小對象分配。該類用於將size和mode元組裝包和拆包到int中。(筆者注:也就是將size和mode組合或者拆分爲int型數據)

    7)分析代碼可知,一個MeasureSpec的模式以下所示,int長度爲32位置,高2位表示mode,後30位用於表示size

           

     8)UNSPECIFIED、EXACTLY、AT_MOST這三個mode的示意圖以下所示:

              

    9)makeMeasureSpec(int mode,int size)用於將mode和size打包成一個int型的MeasureSpec。

    10)getSize(int measureSpec)方法用於從指定的measureSpec值中獲取其size。

    11)getMode(int measureSpec)方法用戶從指定的measureSpec值中獲取其mode。

 

  二、ViewGroup.LayoutParams簡介

   該類的源碼及註釋分析以下所示。

 1 //============================ViewGroup.java===============================
 2 /**
 3      * LayoutParams are used by views to tell their parents how they want to be
 4      * laid out. 
 5      *......
 6      * <p>
 7      * The base LayoutParams class just describes how big the view wants to be
 8      * for both width and height. For each dimension, it can specify one of:
 9      * <ul>
10      * <li>FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which
11      * means that the view wants to be as big as its parent (minus padding)
12      * <li> WRAP_CONTENT, which means that the view wants to be just big enough
13      * to enclose its content (plus padding)
14      * <li> an exact number
15      * </ul>
16      * There are subclasses of LayoutParams for different subclasses of
17      * ViewGroup. For example, AbsoluteLayout has its own subclass of
18      * LayoutParams which adds an X and Y value.</p>
19      * ......
20      * @attr ref android.R.styleable#ViewGroup_Layout_layout_height
21      * @attr ref android.R.styleable#ViewGroup_Layout_layout_width
22      */
23     public static class LayoutParams {
24         ......
25 
26         /**
27          * Special value for the height or width requested by a View.
28          * MATCH_PARENT means that the view wants to be as big as its parent,
29          * minus the parent's padding, if any. Introduced in API Level 8.
30          */
31         public static final int MATCH_PARENT = -1;
32 
33         /**
34          * Special value for the height or width requested by a View.
35          * WRAP_CONTENT means that the view wants to be just large enough to fit
36          * its own internal content, taking its own padding into account.
37          */
38         public static final int WRAP_CONTENT = -2;
39 
40         /**
41          * Information about how wide the view wants to be. Can be one of the
42          * constants FILL_PARENT (replaced by MATCH_PARENT
43          * in API Level 8) or WRAP_CONTENT, or an exact size.
44          */
45         public int width;
46 
47         /**
48          * Information about how tall the view wants to be. Can be one of the
49          * constants FILL_PARENT (replaced by MATCH_PARENT
50          * in API Level 8) or WRAP_CONTENT, or an exact size.
51          */
52         public int height;
53         ......
54 }

 這對其中重要的信息作一些翻譯和整理:

    1)LayoutParams被view用於告訴它們的父佈局它們想要怎樣被佈局。(筆者注:字面意思就是佈局參數)

    2)該LayoutParams基類僅僅描述了view但願寬高有多大。對於每個寬或者高,能夠指定爲如下三種值中的一個:MATCH_PARENT,WRAP_CONTENT,an exact number。(筆者注:FILL_PARENT從API8開始已經被MATCH_PARENT取代了,因此下文就只提MATCH_PARENT)

    3)MATCH_PARENT:意味着該view但願和父佈局尺寸同樣大,若是父佈局有padding,則要減去該padding值。

    4)WRAP_CONTENT:意味着該view但願其大小爲僅僅足夠包裹住其內容便可,若是本身有padding,則要加上該padding值。

    5)對ViewGroup不一樣的子類,也有相應的LayoutParams子類。 

    6)其width和height屬性對應着layout_width和layout_height屬性。

 

  三、View測量的基本流程及重要方法分析

       View體系的測量是從DecorView這個根view開始遞歸遍歷的,而這個View體系樹中包含了衆多的葉子view和ViewGroup的子類容器。這一小節中會從ViewRootImpl.performMeasure()開始,分析測量的基本流程。

     (1)ViewRootImpl.performMeasure()方法

       跟蹤源碼,進入到performMeasure方法分析,這裏僅貼出關鍵流程代碼。

1 //=============ViewRootImpl.java==============
2 private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
3        ......
4        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
5        ......
6 }

 這個mView是誰呢?跟蹤代碼能夠找到給它賦值的地方:

1 //========================ViewRootImpl.java======================
2 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
3       ......
4       mView = view;
5       ......
6 
7       mWindowAttributes.copyFrom(attrs);
8       ......
9 }

       看到這裏,是否是有些似曾相識呢?在第二節的繪製流程中提到過,這裏setView的參數view和attrs是ActivityThread類中addView方法傳遞過來的,因此我們這裏能夠肯定mView指的是DecorView了。上述performMeasure()中,其實就是DecorView在執行measure()操做。若是您這存在「mView不是View類型的嗎,怎麼會指代DecorView做爲整個View體系的根view呢」這樣的疑惑,那這裏就囉嗦一下,DecorView extends FrameLayout extends ViewGroup extends View,經過這個繼承鏈能夠看到,DecorView是一個容器,但ViewGroup也是View的子類,View是全部控件的基類,因此這裏View類型的mView指代DecorView是沒毛病的。

    (2)View.measure()方法

       儘管mView就是DecorView,可是因爲measure()方法是final型的,View子類都不能重寫該方法,因此這裏追蹤measure()的時候就直接進入到View類中了,這裏貼出關鍵流程代碼:

 1 //===========================View.java===============================
 2 /**
 3      * <p>
 4      * This is called to find out how big a view should be. The parent
 5      * supplies constraint information in the width and height parameters.
 6      * </p>
 7      *
 8      * <p>
 9      * The actual measurement work of a view is performed in
10      * {@link #onMeasure(int, int)}, called by this method. Therefore, only
11      * {@link #onMeasure(int, int)} can and must be overridden by subclasses.
12      * </p>
13      *
14      *
15      * @param widthMeasureSpec Horizontal space requirements as imposed by the
16      *        parent
17      * @param heightMeasureSpec Vertical space requirements as imposed by the
18      *        parent
19      *
20      * @see #onMeasure(int, int)
21      */
22 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
23       ......
24       // measure ourselves, this should set the measured dimension flag back
25       onMeasure(widthMeasureSpec, heightMeasureSpec);
26       ......
27 }

        這裏面註釋提供了不少信息,這簡單翻譯並整理一下:

        1)該方法被調用,用於找出view應該多大。父佈局在witdh和height參數中提供了限制信息;

        2)一個view的實際測量工做是在被本方法所調用的onMeasure(int,int)方法中實現的。因此,只有onMeasure(int,int)能夠而且必須被子類重寫(筆者注:這裏應該指的是,ViewGroup的子類必須重寫該方法,才能繪製該容器內的子view。若是是自定義一個子控件,extends View,那麼並非必須重寫該方法);

        3)參數widthMeasureSpec:父佈局加入的水平空間要求;

        4)參數heightMeasureSpec:父佈局加入的垂直空間要求。

       系統將其定義爲一個final方法,可見系統不但願整個測量流程框架被修改。

    (3)View.onMeasure()方法

       在上述方法體內看到onMeasure(int,int)方法時,是否有一絲慰藉呢?終於看到我們最熟悉的身影了,很親切吧!我們編寫自定義View時,基本上都會重寫的方法!我們看看其源碼:

 1 //===========================View.java===============================
 2 /**
 3      * <p>
 4      * Measure the view and its content to determine the measured width and the
 5      * measured height. This method is invoked by {@link #measure(int, int)} and
 6      * should be overridden by subclasses to provide accurate and efficient
 7      * measurement of their contents.
 8      * </p>
 9      *
10      * <p>
11      * <strong>CONTRACT:</strong> When overriding this method, you
12      * <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
13      * measured width and height of this view. Failure to do so will trigger an
14      * <code>IllegalStateException</code>, thrown by
15      * {@link #measure(int, int)}. Calling the superclass'
16      * {@link #onMeasure(int, int)} is a valid use.
17      * </p>
18      *
19      * <p>
20      * The base class implementation of measure defaults to the background size,
21      * unless a larger size is allowed by the MeasureSpec. Subclasses should
22      * override {@link #onMeasure(int, int)} to provide better measurements of
23      * their content.
24      * </p>
25      *
26      * <p>
27      * If this method is overridden, it is the subclass's responsibility to make
28      * sure the measured height and width are at least the view's minimum height
29      * and width ({@link #getSuggestedMinimumHeight()} and
30      * {@link #getSuggestedMinimumWidth()}).
31      * </p>
32      *
33      * @param widthMeasureSpec horizontal space requirements as imposed by the parent.
34      *                         The requirements are encoded with
35      *                         {@link android.view.View.MeasureSpec}.
36      * @param heightMeasureSpec vertical space requirements as imposed by the parent.
37      *                         The requirements are encoded with
38      *                         {@link android.view.View.MeasureSpec}.
39      *
40      * @see #getMeasuredWidth()
41      * @see #getMeasuredHeight()
42      * @see #setMeasuredDimension(int, int)
43      * @see #getSuggestedMinimumHeight()
44      * @see #getSuggestedMinimumWidth()
45      * @see android.view.View.MeasureSpec#getMode(int)
46      * @see android.view.View.MeasureSpec#getSize(int)
47      */
48     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
49         setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
50                 getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
51     }

       函數體內也就一句代碼而已,註釋卻寫了這麼一大堆,可見這個方法的重要性了。這裏翻譯和整理一下這些註釋:

      1)測量該view以及它的內容來決定測量的寬度和高度。該方法被measure(int,int)(筆者注:就是前面提到過的那個方法)調用,而且應該被子類重寫來提供準確並且有效的對它們的內容的測量。

      2)當重寫該方法時,您必須調用setMeasuredDimension(int,int)來存儲該view測量出的寬和高。若是不這樣作將會觸發IllegalStateException,由measure(int,int)拋出。調用基類的onMeasure(int,int)方法是一個有效的方法。

      3)測量的基類實現默認爲背景的尺寸,除非更大的尺寸被MeasureSpec所容許。子類應該重寫onMeasure(int,int)方法來提供對內容更好的測量。

      4)若是該方法被重寫,子類負責確保測量的高和寬至少是該view的mininum高度和mininum寬度值(連接getSuggestedMininumHeight()和getSuggestedMininumWidth());

      5) widthMeasureSpec:父佈局加入的水平空間要求。該要求被編碼到android.view.View.MeasureSpec中。

      6)heightMeasureSpec:父佈局加入的垂直空間要求。該要求被編碼到android.view.View.MeasureSpec中。

       註釋中最後提到了7個方法,這些方法後面會再分析。註釋中花了很多的篇幅對該方法進行說明,但讀者恐怕對其中的一些信息表示有些懵吧,好比MeasureSpec是什麼,mininum高度和mininum寬度值是怎麼回事等,MeasureSpec在本節的開頭介紹過,能夠回頭再看看,其它的後面會做進一步的闡述,到時候我們再回頭來看看這些註釋。

        注意:容器類控件都是ViewGroup的子類,如FrameLayout、LinearLayout等,都會重寫onMeasure方法,根據本身的特性來進行測量;若是是葉子節點view,即最裏層的控件,如TextView等,也可能會重寫onMeasure方法,因此當流程走到onMeasure(...)時,流程可能就會切到那些重寫的onMeasure()方法中去。最後經過從根View到葉子節點的遍歷和遞歸,最終仍是會在葉子view中調用setMeasuredDimension(...)來實現最終的測量。

    (4)View.setMeasuredDimension()方法

      繼續看setMeasuredDimension方法:

 1 /**
 2      * <p>This method must be called by {@link #onMeasure(int, int)} to store the
 3      * measured width and measured height. Failing to do so will trigger an
 4      * exception at measurement time.</p>
 5      *
 6      * @param measuredWidth The measured width of this view.  May be a complex
 7      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
 8      * {@link #MEASURED_STATE_TOO_SMALL}.
 9      * @param measuredHeight The measured height of this view.  May be a complex
10      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
11      * {@link #MEASURED_STATE_TOO_SMALL}.
12      */
13     protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
14         ......
15         setMeasuredDimensionRaw(measuredWidth, measuredHeight);
16     }

   這裏須要重點關注註釋中對參數的說明:

       measuredWidth:該view被測量出寬度值。

       measuredHeight:該view被測量出的高度值。

      到這個時候才正式明確提到寬度和高度,經過getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),參數由widthMeasureSpec變成了measuredWidth,即由「父佈局加入的水平空間要求」轉變爲了view的寬度,measuredHeigh也是同樣。我們先繼續追蹤源碼分析width的值:

 1 /**
 2      * Returns the suggested minimum width that the view should use. This
 3      * returns the maximum of the view's minimum width
 4      * and the background's minimum width
 5      *  ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
 6      * <p>
 7      * When being used in {@link #onMeasure(int, int)}, the caller should still
 8      * ensure the returned width is within the requirements of the parent.
 9      *
10      * @return The suggested minimum width of the view.
11      */
12     protected int getSuggestedMinimumWidth() {
13         return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
14     }

       這個方法是幹嗎用的呢?註釋的翻譯以下:

      1)返回建議該view應該使用的最小寬度值。該方法返回了view的最小寬度值和背景的最小寬度值(連接android.graphics.drawable.Drawable#getMinimumWidth())之間的最大值。

      2)當在onMeasure(int,int)使用時,調用者應該仍然確保返回的寬度值在父佈局的要求以內。

      3)返回值:view的建議最小寬度值。

      這其中提到的"mininum width「指的是在xml佈局文件中該view的「android:minWidth"屬性值,「background's minimum width」值是指「android:background」的寬度。該方法的返回值就是二者之間較大的那一個值,用來做爲該view的最小寬度值,如今應該很容易理解了吧,當一個view在layout文件中同時設置了這兩個屬性時,爲了兩個條件都知足,天然要選擇值大一點的那個了。

 1 /**
 2      * Utility to return a default size. Uses the supplied size if the
 3      * MeasureSpec imposed no constraints. Will get larger if allowed
 4      * by the MeasureSpec.
 5      *
 6      * @param size Default size for this view
 7      * @param measureSpec Constraints imposed by the parent
 8      * @return The size this view should be.
 9      */
10     public static int getDefaultSize(int size, int measureSpec) {
11         int result = size;
12         int specMode = MeasureSpec.getMode(measureSpec);
13         int specSize = MeasureSpec.getSize(measureSpec);
14 
15         switch (specMode) {
16         case MeasureSpec.UNSPECIFIED:
17             result = size;
18             break;
19         case MeasureSpec.AT_MOST:
20         case MeasureSpec.EXACTLY:
21             result = specSize;
22             break;
23         }
24         return result;
25     }

       經過本節開頭的介紹,您應該對MeasureSpec有了一個比較明確的認識了,再看看getDefaultSize(int size,int measureSpec)方法,就很容易理解了。正如其註釋中所說,若是父佈局沒有施加任何限制,即MeasureSpec的mode爲UNSPECIFIED,那麼返回值爲參數中提供的size值。若是父佈局施加了限制,則返回的默認尺寸爲保存在參數measureSpec中的specSize值。因此到目前爲止,須要繪製的寬和高值就被肯定下來了。只是,咱們還須要明確這兩個值最初是從哪裏傳過來的,後面咱們還會順藤摸瓜,找到這兩個尺寸的出處。

       既然寬度值measuredWidth和高度值measuredHeight已經肯定下來,咱們繼續追蹤以前的setMeasuredDimension(int measuredWidth, int measuredHeight)方法,其內部最後調用了以下的方法:

 1 /**
 2      * ......
 3      * @param measuredWidth The measured width of this view.  May be a complex
 4      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
 5      * {@link #MEASURED_STATE_TOO_SMALL}.
 6      * @param measuredHeight The measured height of this view.  May be a complex
 7      * bit mask as defined by {@link #MEASURED_SIZE_MASK} and
 8      * {@link #MEASURED_STATE_TOO_SMALL}.
 9      */
10     private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
11         mMeasuredWidth = measuredWidth;
12         mMeasuredHeight = measuredHeight;
13         ......
14     }

       到目前爲止,View中的成員變量mMeasureWidth和mMeasureHeight就被賦值了,這也就意味着,View的測量就結束了。前面講onMeasure()方法時介紹過,View子類(包括ViewGroup子類)一般會重寫onMeasure(),當閱讀FrameLayout、LinearLayout、TextView等重寫的onMeasure()方法時,會發現它們最終都會調用setMeasuredDimension() 方法,從而完成測量。這裏能夠對應上前面介紹View.onMeasure()時,翻譯註釋的第2)點以及setMeasuredDimension()方法的註釋說明。

    (5)getMeasureWidth()方法

       在View的onMeasure()方法的註釋中提到了該方法,這裏順便也介紹一下。

1 //==================View.java==============
2 public static final int MEASURED_SIZE_MASK = 0x00ffffff;
3 /**
4  * ......
5  * @return The raw measured width of this view.
6  */
7 public final int getMeasuredWidth() {
8    return mMeasuredWidth & MEASURED_SIZE_MASK;
9 }

       獲取原始的測量寬度值,通常會拿這個方法和layout執行後getWidth()方法作比較。該方法須要在setMeasuredDimension()方法執行後纔有效,不然返回值爲0。

    (6)getMeasureHeight()方法

       在View的onMeasure()方法的註釋中提到了該方法,這裏順便也介紹一下。

1 //==================View.java==============
2 /**
3   * ......
4   * @return The raw measured height of this view.
5   */
6 public final int getMeasuredHeight() {
7    return mMeasuredHeight & MEASURED_SIZE_MASK;
8 }

       獲取原始的測量高度值,通常會拿這個方法和layout執行後getHeight()方法作比較。該方法須要在setMeasuredDimension()方法執行後纔有效,不然返回值爲0。

 

  四、performMeasure()方法中RootMeasureSpec參數來源分析

       前面講到getDefaultSize(int size,int measureSpec)方法時提到過,要找到其中measureSpec的來源。事實上,根據View體系的不斷往下遍歷和遞歸中,前面流程中傳入getDefaultSize()方法中的值是根據上一次的值變更的,因此我們須要找到最初參數值。根據代碼往回看,能夠看到前文performTraversals()源碼部分第三行和第四行中,該參數的來源。我們先看看傳入performMeasure(int,int)的childWidthMeasureSpec是怎麼來的。

int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);

       getRootMeasureSpec(int,int)方法的完整源碼以下所示:

 1 /**
 2      * Figures out the measure spec for the root view in a window based on it's
 3      * layout params.
 4      *
 5      * @param windowSize
 6      *            The available width or height of the window
 7      *
 8      * @param rootDimension
 9      *            The layout params for one dimension (width or height) of the
10      *            window.
11      *
12      * @return The measure spec to use to measure the root view.
13      */
14     private static int getRootMeasureSpec(int windowSize, int rootDimension) {
15         int measureSpec;
16         switch (rootDimension) {
17 
18         case ViewGroup.LayoutParams.MATCH_PARENT:
19             // Window can't resize. Force root view to be windowSize.
20             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
21             break;
22         case ViewGroup.LayoutParams.WRAP_CONTENT:
23             // Window can resize. Set max size for root view.
24             measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
25             break;
26         default:
27             // Window wants to be an exact size. Force root view to be that size.
28             measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
29             break;
30         }
31         return measureSpec;
32     }

 照例先翻譯一下注釋

      1)基於window的layout params,在window中爲root view 找出measure spec。(筆者注:也就是找出DecorView的MeasureSpec,這裏的window也就是PhoneWindow了)

      2)參數windowSize:window的可用寬度和高度值。

      3)參數rootDimension:window的寬/高的layout param值。

      4)返回值:返回用於測量root view的MeasureSpec。    

       若是不清楚LayoutParams類,能夠看看本節開頭的介紹。在getRootMeasureSpec(int,int)中,MeasureSpec.makeMeasureSpec方法在前面介紹MeasureSpec類的時候提到過,就是將size和mode組合成一個MeasureSpec值。這裏咱們能夠看到ViewGroup.LayoutParam的width/height值和MeasureSpec的mode值存在以下的對應關係:

       咱們再繼續看看windowSize和rootDimension的實際參數mWidth和lp.width的來歷。

 1 //===========================ViewRootImpl.java=======================
 2 ......
 3 final Rect mWinFrame; // frame given by window manager.
 4 ......
 5 private void performTraversals() {
 6     ......
 7     Rect frame = mWinFrame;
 8     ......
 9     mWidth = frame.width();
10     ......
11 }

       從源碼中對mWinFrame的註釋來看,是由WindowManager提供的,該矩形正好是整個屏幕(這裏暫時尚未在源碼中找到明確的證據,後續找到後再補上)。在文章【Android圖形系統(三)-View繪製流程】的「2.2 窗口布局階段」中有提到,WindowManagerService服務計算Activity窗口的大小,並將Activity窗口的大小保存在成員變量mWinFrame中。對Activity窗口大小計算的詳情,有興趣的能夠閱讀一下大神羅昇陽的博文【Android窗口管理服務WindowManagerService計算Activity窗口大小的過程分析】。

 1 //=================================ViewRootImpl.java================================
 2 ......
 3 final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
 4 ......
 5 public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
 6     ......
 7     mWindowAttributes.copyFrom(attrs);
 8     ......
 9 }
10 private void performTraversals() {
11      ......
12      WindowManager.LayoutParams lp = mWindowAttributes;
13      ......     
14 }

       第5行setView方法,在上一節中講過,其中的參數就是ActivityThread類中傳過來的,attrs是PhoneWindow的LayoutParams值,在第三節中就專門講過這個參數,其width和height屬性值均爲LayoutParams.MATCH_PARENT。結合getRootMeasureSpec(int windowSize, int rootDimension)方法,能夠得出以下結果:

      

       此時,咱們就獲得了DecorView的MeasureSpec了,後面的遞歸操做就是在此基礎上不斷將測量要求從父佈局傳遞到子view。

 

  五、ViewGroup中輔助重寫onMeasure的幾個重要方法介紹

        前面咱們介紹的不少方法都是View類中提供的,ViewGroup中也提供了一些方法用於輔助ViewGroup子類容器的測量。這裏重點介紹三個方法:measureChild(...)、measureChildWithMargins(...)和measureChildWithMargins(...)方法。

    (1)measureChild()方法和measureChildWithMargins()方法

 1 //================ViewGroup.java===============
 2 /**
 3      * Ask one of the children of this view to measure itself, taking into
 4      * account both the MeasureSpec requirements for this view and its padding.
 5      * The heavy lifting is done in getChildMeasureSpec.
 6      *
 7      * @param child The child to measure
 8      * @param parentWidthMeasureSpec The width requirements for this view
 9      * @param parentHeightMeasureSpec The height requirements for this view
10      */
11     protected void measureChild(View child, int parentWidthMeasureSpec,
12             int parentHeightMeasureSpec) {
13         final LayoutParams lp = child.getLayoutParams();
14 
15         final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
16                 mPaddingLeft + mPaddingRight, lp.width);
17         final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
18                 mPaddingTop + mPaddingBottom, lp.height);
19 
20         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
21     }

 

 1 //===================ViewGroup.java===================
 2 /**
 3      * Ask one of the children of this view to measure itself, taking into
 4      * account both the MeasureSpec requirements for this view and its padding
 5      * and margins. The child must have MarginLayoutParams The heavy lifting is
 6      * done in getChildMeasureSpec.
 7      *
 8      * @param child The child to measure
 9      * @param parentWidthMeasureSpec The width requirements for this view
10      * @param widthUsed Extra space that has been used up by the parent
11      *        horizontally (possibly by other children of the parent)
12      * @param parentHeightMeasureSpec The height requirements for this view
13      * @param heightUsed Extra space that has been used up by the parent
14      *        vertically (possibly by other children of the parent)
15      */
16     protected void measureChildWithMargins(View child,
17             int parentWidthMeasureSpec, int widthUsed,
18             int parentHeightMeasureSpec, int heightUsed) {
19         final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
20 
21         final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
22                 mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
23                         + widthUsed, lp.width);
24         final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
25                 mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
26                         + heightUsed, lp.height);
27 
28         child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
29     }

        對比這兩個方法能夠發現,它們很是類似,從註釋上來看,後者在前者的基礎上增長了已經使用的寬高和margin值。其實它們的功能都是同樣的,最後都是生成子View的MeasureSpec,並傳遞給子View繼續測量,即最後一句代碼child.measure(childWidthMeasureSpec, childHeightMeasureSpec)。通常根據容器自身的須要來選擇其中一個,好比,在FrameLayout和LinearLayout中重寫的onMeasure方法中調用的就是後者,而AbsoluteLayout中就是間接地調用的前者。而RelativeLayout中,二者都沒有調用,而是本身寫了一套方法,不過該方法和後者方法僅略有差異,但基本功能仍是同樣,讀者能夠本身去看看它們的源碼,這裏就不貼出來了。

    (2)getChildMeasureSpec()方法

       前兩個方法中都用到了這個方法,它很重要,它用於將父佈局傳遞來的MeasureSpec和其子view的LayoutParams,整合爲一個最有可能的子View的MeasureSpec。

 1 //==================ViewGroup.java====================
 2  /**
 3      * Does the hard part of measureChildren: figuring out the MeasureSpec to
 4      * pass to a particular child. This method figures out the right MeasureSpec
 5      * for one dimension (height or width) of one child view.
 6      *
 7      * The goal is to combine information from our MeasureSpec with the
 8      * LayoutParams of the child to get the best possible results. For example,
 9      * if the this view knows its size (because its MeasureSpec has a mode of
10      * EXACTLY), and the child has indicated in its LayoutParams that it wants
11      * to be the same size as the parent, the parent should ask the child to
12      * layout given an exact size.
13      *
14      * @param spec The requirements for this view
15      * @param padding The padding of this view for the current dimension and
16      *        margins, if applicable
17      * @param childDimension How big the child wants to be in the current
18      *        dimension
19      * @return a MeasureSpec integer for the child
20      */
21     public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
22         int specMode = MeasureSpec.getMode(spec);
23         int specSize = MeasureSpec.getSize(spec);
24 
25         int size = Math.max(0, specSize - padding);
26 
27         int resultSize = 0;
28         int resultMode = 0;
29 
30         switch (specMode) {
31         // Parent has imposed an exact size on us
32         case MeasureSpec.EXACTLY:
33             if (childDimension >= 0) {
34                 resultSize = childDimension;
35                 resultMode = MeasureSpec.EXACTLY;
36             } else if (childDimension == LayoutParams.MATCH_PARENT) {
37                 // Child wants to be our size. So be it.
38                 resultSize = size;
39                 resultMode = MeasureSpec.EXACTLY;
40             } else if (childDimension == LayoutParams.WRAP_CONTENT) {
41                 // Child wants to determine its own size. It can't be
42                 // bigger than us.
43                 resultSize = size;
44                 resultMode = MeasureSpec.AT_MOST;
45             }
46             break;
47 
48         // Parent has imposed a maximum size on us
49         case MeasureSpec.AT_MOST:
50             if (childDimension >= 0) {
51                 // Child wants a specific size... so be it
52                 resultSize = childDimension;
53                 resultMode = MeasureSpec.EXACTLY;
54             } else if (childDimension == LayoutParams.MATCH_PARENT) {
55                 // Child wants to be our size, but our size is not fixed.
56                 // Constrain child to not be bigger than us.
57                 resultSize = size;
58                 resultMode = MeasureSpec.AT_MOST;
59             } else if (childDimension == LayoutParams.WRAP_CONTENT) {
60                 // Child wants to determine its own size. It can't be
61                 // bigger than us.
62                 resultSize = size;
63                 resultMode = MeasureSpec.AT_MOST;
64             }
65             break;
66 
67         // Parent asked to see how big we want to be
68         case MeasureSpec.UNSPECIFIED:
69             if (childDimension >= 0) {
70                 // Child wants a specific size... let him have it
71                 resultSize = childDimension;
72                 resultMode = MeasureSpec.EXACTLY;
73             } else if (childDimension == LayoutParams.MATCH_PARENT) {
74                 // Child wants to be our size... find out how big it should
75                 // be
76                 resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
77                 resultMode = MeasureSpec.UNSPECIFIED;
78             } else if (childDimension == LayoutParams.WRAP_CONTENT) {
79                 // Child wants to determine its own size.... find out how
80                 // big it should be
81                 resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
82                 resultMode = MeasureSpec.UNSPECIFIED;
83             }
84             break;
85         }
86         //noinspection ResourceType
87         return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
88     }

 我們依然先翻譯和整理一下開頭的註釋:

      1)處理measureChildren的困難部分:計算出Measure傳遞給指定的child。該方法計算出一個子view的寬或高的正確MeasureSpec。

      2)其目的是組合來自咱們MeasureSpec的信息和child的LayoutParams來獲得最有可能的結果。好比:若是該view知道它的尺寸(由於它的MeasureSpec的mode爲EXACTLY),而且它的child在它的LayoutParams中表示它想和父佈局有同樣大,那麼父佈局應該要求該child按照精確的尺寸進行佈局。

      3)參數spec:對該view的要求(筆者注:父佈局對當前child的MeasureSpec要求)

      4)參數padding:該view寬/高的padding和margins值,若是可應用的話。

      5)參數childDimension:該child在寬/高上但願多大。

      6)返回:返回該child的MeasureSpec整數。

       若是明白了前文中對MeasureSpec的介紹後,這一部分的代碼應該就容易理解了,specMode的三種值,LayoutParams的width和height的三種值,以及和layout_width、layout_height之間的關對應關係,在文章的開頭已經介紹過了,不明白的能夠再回頭複習一下。specMode和specSize分別是父佈局傳下來的要求,size的值是父佈局尺寸要求減去其padding值,最小不會小於0。代碼最後就是將從新獲得的mode和size組合生成一個新的MeasureSpec,傳遞給子View,一直遞歸下去,該方法也在前面講過。本段代碼重難點就是這裏新mode和新size值的肯定,specMode和childDimension各有3種值,因此最後會有9種組合。若是對這段代碼看不明白的,能夠看看筆者對這段代碼的解釋(width和height同理,這裏以width爲例):

  • 若是specMode的值爲MeasureSpec.EXACTLY,即父佈局對子view的尺寸要求是一個精確值,這有兩種狀況,父佈局中layout_width屬性值被設置爲具體值,或者match_parent,它們都被定義爲精確值。針對childDimension的值

          i)childDimension也爲精確值時。它是LayoutParams中width屬性,是一個具體值,不包括match_parent狀況,這個必定要和MeasureSpec中的精確值EXACTLY區別開來。此時resultSize爲childDimension的精確值,resultMode理所固然爲MeasureSpec.EXACTLY。這裏不知道讀者會不會又疑問,若是子View的layout_width值比父佈局的大,那這個結論還成立嗎?按照咱們的經驗,彷佛不太能理解,由於子view的寬度再怎麼樣也不會比父佈局大。事實上,咱們平時經驗看到的,是最後佈局後繪製出來的結果,而當前步驟爲測量值,是有差異的。讀者能夠自定義一個View,將父佈局layout_width設置爲100px,該自定義的子view則設置爲200px,而後在子view中重寫的onMeasure方法中打印出getMeasuredWidth()值看看,其值必定是200。甚至若是子view設置的值超過屏幕尺寸,其打印值也是設置的值。

        ii)childDimension值爲LayoutParams.MATCH_PARENT時。這個容易理解,它的尺寸和父佈局同樣,也是個精確值,因此resultSize爲前面求出的size值,由父佈局決定,resultMode爲MeasureSpec.EXACTLY。

        iii)childDimension值爲LayoutParams.WRAP_CONTENT時。當子view的layout_width被設置爲wrap_content時,即便最後咱們肉眼看到屏幕上真正顯示出來的控件很小,但在測量時和父佈局同樣的大小。這一點仍然能夠經過打印getMeasuredWidth值來理解。因此必定不要被「經驗」所誤。因此resultSize值爲size大小,resultMode爲MeasureSpec.AT_MOST。

  • 若是specMode值爲MeasureSpec.AT_MOST。其對應於layout_width爲wrap_content,此時,咱們能夠想象到,子View對結果的決定性很大。

        i)childDimension爲精確值時。很容易明確specSize爲自身的精確值,specMode爲MeasureSpec.EXACTLY。

        ii)childDimension爲LayoutParams.MATCH_PARENT時。specSize由父佈局決定,爲size;specMode爲MeasureSpec.AT_MOST。

        iii)childDimension爲LayoutParams.WRAP_CONTENT時。specSize由父佈局決定,爲size;specMode爲MeasureSpec.AT_MOST。

  • 若是specMode值爲MeasureSpec.UNSPECIFIED。前面說過,平時不多用,通常用在系統中,不過這裏仍是簡單說明一下。這一段有個變量View.sUseZeroUnspecifiedMeasureSpec,它是用於表示當前的目標api是否低於23(對應系統版本爲Android M)的,低於23則爲true,不然爲false。如今系統版本基本上都是Android M及以上的,因此這裏該值咱們當成false來處理。

        i)childDimension爲精確值時。很容易明確specSize爲自身的精確值,specMode爲MeasureSpec.EXACTLY。

        ii)childDimension爲LayoutParams.MATCH_PARENT時。specSize由父佈局決定,爲size;specMode和父佈局同樣,爲MeasureSpec.UNSPECIFIED。

        iii)childDimension爲LayoutParams.WRAP_CONTENT時。specSize由父佈局決定,爲size;specMode和父佈局同樣,爲MeasureSpec.UNSPECIFIED。

       這個方法對理解測量時MeasureSpec的傳遞過程很是重要,而且須要記憶和理解的內容也不是,因此這裏花的篇幅比較多。

 

       經過這一節,咱們介紹了ViewGroup在測量過程當中要用到的方法。經過這些方法,咱們更加深刻理解了測量過程當中ViewGroup是如何測量子View的了。

 

  六、DecorView測量的大體流程

       前面咱們提到過DecorView的繼承鏈:DecorView extends FrameLayout extends ViewGroup extends View。因此在這個繼承過程當中必定會有子類重寫onMeasure方法,當DecorView第一次調用到measure()方法後,流程就開始切換到重寫的onMeasure()中了。咱們按照這個繼承順序看看measure流程的相關源碼:

 1 //=============DecorView.java=============
 2 @Override
 3 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
 4        ......
 5     super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 6        ......
 7 }
 8 
 9 //=============FrameLayout.java=============
10 @Override
11 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
12   int count = getChildCount();
13   for (int i = 0; i < count; i++) {
14        final View child = getChildAt(i);
15        ......
16        measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
17        ......             
18    }
19    ......
20    setMeasuredDimension(......)
21    ...... }

       第17行中measureChildWithMargins()方法是ViewGroup提供的方法,前面咱們介紹過了。從上述FrameLayout中重寫的onMeasure方法中能夠看到,是先把子view測量完成後,最後纔去調用setMeasuredDimension(...)來測量本身的。事實上,整個測量過程就是從子view開始測量,而後一層層往上再測量父佈局,直到DecorView爲止的。

       可能到這裏有些讀者會有個疑問,DecorView中onMeasure方法的參數值是從哪裏傳過來的呢?呵呵,前面花了很大的篇幅,就在不斷地講它倆,這裏再強調囉嗦一次:

1 //=====================ViewRootImpl.java=================
2 private void performTraversals() {
3    ......
4    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
5    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);      
6    ......
7 }

 若是仍是不明白,回過頭去再看看這部分的說明吧,這裏就再也不贅述了。

 

  七、DecorView視圖樹的簡易measure流程圖

        到目前爲止,DecorView的整個測量流程就接上了,從ViewRootImpl類的performTraversals()開始,通過遞歸遍歷,最後到葉子view測量結束,DecorView視圖樹的測量就完成了。這裏再用一個流程圖簡單描述一下整個流程:

  

 

       在這一節的最後,推薦一篇博文,這裏面有個很是詳細的案例分析,如何一步一步從DecorView開始遍歷,到整個View樹測量完成,以及如何測量出每一個view的寬高值:【Android View的繪製流程:https://www.jianshu.com/p/5a71014e7b1b?from=singlemessage】Measure過程的第4點。認真分析完該實例,必定會對測量過程有個更深入的認識。

 

6、layout過程分析

       當measure過程完成後,接下來就會進行layout階段,即佈局階段。在前面measure的做用是測量每一個view的尺寸,而layout的做用是根據前面測量的尺寸以及設置的其它屬性值,共同來肯定View的位置。

  一、performLayout方法引出DecorView的佈局流程

       測量完成後,會在ViewRootImpl類的performTraverserals()方法中,開始調用performLayout方法:

performLayout(lp, mWidth, mHeight);

       傳入該方法的參數咱們在上一節中已經分析過了,lp中width和height均爲LayoutParams.MATCH_PARENT,mWidth和mHeight分別爲屏幕的寬高。

1 //=====================ViewRootImpl.java===================
2 private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
3             int desiredWindowHeight) {
4    ......
5    final View host = mView;
6    ......
7    host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
8    ......
9 }

       mView的值上一節也講過,就是DecorView,佈局流程也是從DecorView開始遍歷和遞歸。

 

  二、layout方法正式啓動佈局流程

       因爲DecorView是一個容器,是ViewGroup子類,因此跟蹤代碼的時候,其實是先進入到ViewGroup類中的layout方法中。

 1 //==================ViewGroup.java================
 2     @Override
 3     public final void layout(int l, int t, int r, int b) {
 4         if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
 5             if (mTransition != null) {
 6                 mTransition.layoutChange(this);
 7             }
 8             super.layout(l, t, r, b);
 9         } else {
10             // record the fact that we noop'd it; request layout when transition finishes
11             mLayoutCalledWhileSuppressed = true;
12         }
13     }

       這是一個final類型的方法,因此自定義 的ViewGroup子類沒法重寫該方法,可見系統不但願自定義的ViewGroup子類破壞layout流程。繼續追蹤super.layout方法,又跳轉到了View中的layout方法。

 1 //=================View.java================
 2  /**
 3      * Assign a size and position to a view and all of its
 4      * descendants
 5      *
 6      * <p>This is the second phase of the layout mechanism.
 7      * (The first is measuring). In this phase, each parent calls
 8      * layout on all of its children to position them.
 9      * This is typically done using the child measurements
10      * that were stored in the measure pass().</p>
11      *
12      * <p>Derived classes should not override this method.
13      * Derived classes with children should override
14      * onLayout. In that method, they should
15      * call layout on each of their children.</p>
16      *
17      * @param l Left position, relative to parent
18      * @param t Top position, relative to parent
19      * @param r Right position, relative to parent
20      * @param b Bottom position, relative to parent
21      */
22     @SuppressWarnings({"unchecked"})
23     public void layout(int l, int t, int r, int b) {
24         ......
25         boolean changed = isLayoutModeOptical(mParent) ?
26                 setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);  
27         if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
28             onLayout(changed, l, t, r, b);
29             ......
30          }
31          ......
32 }

 先翻譯一下注釋中對該方法的描述:

      1)給view和它的全部後代分配尺寸和位置。

      2)這是佈局機制的第二個階段(第一個階段是測量)。在這一階段中,每個父佈局都會對它的子view進行佈局來放置它們。通常來講,該過程會使用在測量階段存儲的child測量值。

      3)派生類不該該重寫該方法。有子view的派生類(筆者注:也就是容器類,父佈局)應該重寫onLayout方法。在重寫的onLayout方法中,它們應該爲每一子view調用layout方法進行佈局。

      4)參數依次爲:Left、Top、Right、Bottom四個點相對父佈局的位置。

 

  三、setFrame方法真正執行佈局任務

       在上面的方法體中,咱們先重點看看setFrame方法。至於setOpticalFrame方法,其中也是調用的setFrame方法。

 1 //=================View.java================
 2 /**
 3      * Assign a size and position to this view.
 4      *
 5      * This is called from layout.
 6      *
 7      * @param left Left position, relative to parent
 8      * @param top Top position, relative to parent
 9      * @param right Right position, relative to parent
10      * @param bottom Bottom position, relative to parent
11      * @return true if the new size and position are different than the
12      *         previous ones
13      * {@hide}
14      */
15     protected boolean setFrame(int left, int top, int right, int bottom) {
16         boolean changed = false;
17         ......
18         if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
19             changed = true;
20             ......
21             int oldWidth = mRight - mLeft;
22             int oldHeight = mBottom - mTop;
23             int newWidth = right - left;
24             int newHeight = bottom - top;
25             boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
26 
27             // Invalidate our old position
28             invalidate(sizeChanged);
29 
30             mLeft = left;
31             mTop = top;
32             mRight = right;
33             mBottom = bottom;
34             ......
35         }
36         return changed;
37  }

  註釋中重要的信息有:

      1)該方法用於給該view分配尺寸和位置。(筆者注:也就是實際的佈局工做是在這裏完成的)

      2)返回值:若是新的尺寸和位置和以前的不一樣,返回true。(筆者注:也就是該view的位置或大小發生了變化)

       在方法體中,從第27行開始,對view的四個屬性值進行了賦值,即mLeft、mTop、mRight、mBottom四條邊界座標被肯定,代表這裏完成了對該View的佈局。

 

  四、onLayout方法讓父佈局調用對子view的佈局

      再返回到layout方法中,會看到若是view發生了改變,接下來會調用onLayout方法,這和measure調用onMeasure方法相似。

 1 //============View.java============
 2 /**
 3      * Called from layout when this view should
 4      * assign a size and position to each of its children.
 5      *
 6      * Derived classes with children should override
 7      * this method and call layout on each of
 8      * their children.
 9      * @param changed This is a new size or position for this view
10      * @param left Left position, relative to parent
11      * @param top Top position, relative to parent
12      * @param right Right position, relative to parent
13      * @param bottom Bottom position, relative to parent
14      */
15     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
16     }

 先翻譯一下關鍵註釋:

      1)當該view要分配尺寸和位置給它的每個子view時,該方法會從layout方法中被調用。

      2)有子view的派生類(筆者注:也就是容器,父佈局)應該重寫該方法而且爲每個子view調用layout。

       咱們發現這是一個空方法,由於layout過程是父佈局容器佈局子view的過程,onLayout方法葉子view沒有意義,只有ViewGroup纔有用。因此,若是當前View是一個容器,那麼流程會切到被重寫的onLayout方法中。咱們先看ViewGroup類中的重寫:

1 //=============ViewGroup.java===========
2   @Override
3    protected abstract void onLayout(boolean changed,
4            int l, int t, int r, int b);

       進入到ViewGroup類中發現,該方法被定義爲了abstract方法,因此之後凡是直接繼承自ViewGroup類的容器,就必需要重寫onLayout方法。 事實上,layout流程是繪製流程中必需的過程,而前面講過的measure流程,其實能夠不要,這一點等會再說。

       我們先直接進入到DecorView中查看重寫的onLayout方法。

1 //==============DecorView.java================
2  @Override
3  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
4      super.onLayout(changed, left, top, right, bottom);
5      ......
6 }

       DecerView繼承自FrameLayout,我們繼續到FrameLayout類中重寫的onLayout方法看看。

 1 //================FrameLayout.java==============
 2     @Override
 3     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
 4         layoutChildren(left, top, right, bottom, false /* no force left gravity */);
 5     }
 6 
 7     void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
 8         final int count = getChildCount();
 9         ......
10         for (int i = 0; i < count; i++) {
11              final View child = getChildAt(i);
12              if (child.getVisibility() != GONE) {
13                  final LayoutParams lp = (LayoutParams) child.getLayoutParams();
14 
15                  final int width = child.getMeasuredWidth();
16                  final int height = child.getMeasuredHeight();
17                  ......
18                  child.layout(childLeft, childTop, childLeft + width, childTop + height);
19             }
20     }

       這裏僅貼出關鍵流程的代碼,我們能夠看到,這裏面也是對每個child調用layout方法的。若是該child仍然是父佈局,會繼續遞歸下去;若是是葉子view,則會走到view的onLayout空方法,該葉子view佈局流程走完。另外,咱們看到第15行和第16行中,width和height分別來源於measure階段存儲的測量值,若是這裏經過其它渠道賦給width和height值,那麼measure階段就不須要了,這也就是我前面提到的,onLayout是必須要實現的(不只會報錯,更重要的是不對子view佈局的話,這些view就不會顯示了),而measure過程能夠不要。固然,確定是不建議這麼作的,採用其它方式很實現咱們要的結果。

 

  五、DecorView視圖樹的簡易佈局流程圖

       若是是前面搞清楚了DecorView視圖樹的測量流程,那這一節的佈局流程也就很是好理解了,我們這裏再簡單梳理一下:

 

 

7、draw過程分析

       當layout完成後,就進入到draw階段了,在這個階段,會根據layout中肯定的各個view的位置將它們畫出來。該過程的分析思路和前兩個過程相似,若是前面讀懂了,那這個流程也就很容易理解了。

  一、從performDraw方法到draw方法

       draw過程,天然也是從performTraversals()中的performDraw()方法開始的,我們從該方法追蹤,我們這裏僅貼出關鍵流程代碼,至於其它的邏輯,不是本文的重點,這裏就先略過,有興趣的能夠自行研究。

 1 //==================ViewRootImpl.java=================
 2 private void performDraw() {
 3       ......
 4       boolean canUseAsync = draw(fullRedrawNeeded);
 5       ......
 6 }
 7 
 8 private boolean draw(boolean fullRedrawNeeded) {
 9       ......
10       if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset,
11                         scalingRequired, dirty, surfaceInsets)) {
12                     return false;
13                 }
14       ......
15 }
16 
17 private boolean drawSoftware(......){
18       ......
19       mView.draw(canvas);
20       ......
21 }

       前面咱們講過了,這mView就是DecorView,這樣就開始了DecorView視圖樹的draw流程了。

  二、DecorView樹遞歸完成「畫」流程

       DecorView類中重寫了draw()方法,追蹤源碼後進入到該部分。

1 //================DecorView.java==============
2 @Override
3 public void draw(Canvas canvas) {
4      super.draw(canvas);
5 
6      if (mMenuBackground != null) {
7          mMenuBackground.draw(canvas);
8      }
9 }

       從這段代碼來看, 調用完super.draw後,還畫了菜單背景,固然super.draw是我們關注的重點,這裏還作了啥我們不用太關心。因爲FrameLayout和ViewGroup都沒有重寫該方法,因此就直接進入都了View類中的draw方法了。

 1 //====================View.java===================== 
 2  /**
 3      * Manually render this view (and all of its children) to the given Canvas.
 4      * The view must have already done a full layout before this function is
 5      * called.  When implementing a view, implement
 6      * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
 7      * If you do need to override this method, call the superclass version.
 8      *
 9      * @param canvas The Canvas to which the View is rendered.
10      */
11     @CallSuper
12     public void draw(Canvas canvas) {
13        ......
14         /*
15          * Draw traversal performs several drawing steps which must be executed
16          * in the appropriate order:
17          *
18          *      1. Draw the background
19          *      2. If necessary, save the canvas' layers to prepare for fading
20          *      3. Draw view's content
21          *      4. Draw children
22          *      5. If necessary, draw the fading edges and restore layers
23          *      6. Draw decorations (scrollbars for instance)
24          */
25 
26         // Step 1, draw the background, if needed
27         int saveCount;
28 
29         if (!dirtyOpaque) {
30             drawBackground(canvas);
31         }
32 
33         // skip step 2 & 5 if possible (common case)
34         ......
35         // Step 3, draw the content
36         if (!dirtyOpaque) onDraw(canvas);
37 
38         // Step 4, draw the children
39         dispatchDraw(canvas);
40         ......
41         // Step 6, draw decorations (foreground, scrollbars)
42         onDrawForeground(canvas);45         ......
43     }

      這段代碼描述了draw階段完成的7個主要步驟,這裏我們先翻譯一下其註釋:

      1)手動渲染該view(以及它的全部子view)到給定的畫布上。

      2)在該方法調用以前,該view必須已經完成了全面的佈局。當正在實現一個view是,實現onDraw(android.graphics.Cavas)而不是本方法。若是您確實須要重寫該方法,調用超類版本。

      3)參數canvas:將view渲染到的畫布。

      從代碼上看,這裏作了不少工做,我們簡單說明一下,有助於理解這個「畫」工做。

      1)第一步:畫背景。對應我咱們在xml佈局文件中設置的「android:background」屬性,這是整個「畫」過程的第一步,這一步是不重點,知道這裏幹了什麼就行。

      2)第二步:畫內容(第2步和第5步只有有須要的時候纔用到,這裏就跳過)。好比TextView的文字等,這是重點,onDraw方法,後面詳細介紹。

      3)第三步:畫子view。dispatchDraw方法用於幫助ViewGroup來遞歸畫它的子view。這也是重點,後面也要詳細講到。

      4)第四步:畫裝飾。這裏指畫滾動條和前景。其實平時的每個view都有滾動條,只是沒有顯示而已。一樣這也不是重點,知道作了這些事就行。

       我們進入onDraw方法看看

1 //=================View.java===============
2 /**
3      * Implement this to do your drawing.
4      *
5      * @param canvas the canvas on which the background will be drawn
6      */
7     protected void onDraw(Canvas canvas) {
8     }

 註釋中說:實現該方法來作「畫」工做。也就是說,具體的view須要重寫該方法,來畫本身想展現的東西,如文字,線條等。DecorView中重寫了該方法,因此流程會走到DecorView中重寫的onDraw方法。

1 //===============DocerView.java==============
2 @Override
3     public void onDraw(Canvas c) {
4         super.onDraw(c);
5       mBackgroundFallback.draw(this, mContentRoot, c, mWindow.mContentParent,
6         mStatusColorViewState.view, mNavigationColorViewState.view);
7  }

      這裏調用了onDraw的父類方法,同時第4行還畫了本身特定的東西。因爲FrameLayout和ViewGroup也沒有重寫該方法,且View中onDraw爲空方法,因此super.onDraw方法實際上是啥都沒幹的。DocerView畫完本身的東西,緊接着流程就又走到dispatchDraw方法了。

 1 //================View.java===============
 2 /**
 3      * Called by draw to draw the child views. This may be overridden
 4      * by derived classes to gain control just before its children are drawn
 5      * (but after its own view has been drawn).
 6      * @param canvas the canvas on which to draw the view
 7      */
 8     protected void dispatchDraw(Canvas canvas) {
 9 
10     }

       先看看註釋:被draw方法調用來畫子View。該方法可能會被派生類重寫來獲取控制,這個過程正好在該view的子view被畫以前(但在它本身被畫完成後)。

       也就是說當本view被畫完以後,就開始要畫它的子view了。這個方法也是一個空方法,實際上對於葉子view來講,該方法沒有什麼意義,由於它沒有子view須要畫了,而對於ViewGroup來講,就須要重寫該方法來畫它的子view。

       在源碼中發現,像平時經常使用的LinearLayout、FrameLayout、RelativeLayout等經常使用的佈局控件,都沒有再重寫該方法,DecorView中也同樣,而是隻在ViewGroup中實現了dispatchDraw方法的重寫。因此當DecorView執行完onDraw方法後,流程就會切到ViewGroup中的dispatchDraw方法了。

 1 //=============ViewGroup.java============
 2  @Override
 3  protected void dispatchDraw(Canvas canvas) {
 4         final int childrenCount = mChildrenCount;
 5         final View[] children = mChildren;
 6         ......
 7         for (int i = 0; i < childrenCount; i++) {
 8             more |= drawChild(canvas, child, drawingTime);
 9             ......
10         }
11         ...... 
12  }

       從上述源碼片斷能夠發現,這裏其實就是對每個child執行drawChild操做。

 1 /**
 2      * Draw one child of this View Group. This method is responsible for getting
 3      * the canvas in the right state. This includes clipping, translating so
 4      * that the child's scrolled origin is at 0, 0, and applying any animation
 5      * transformations.
 6      *
 7      * @param canvas The canvas on which to draw the child
 8      * @param child Who to draw
 9      * @param drawingTime The time at which draw is occurring
10      * @return True if an invalidate() was issued
11      */
12     protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
13         return child.draw(canvas, this, drawingTime);
14     }

先翻譯註釋的內容:

      1)畫當前ViewGroup中的某一個子view。該方法負責在正確的狀態下獲取畫布。這包括了裁剪,移動,以便子view的滾動原點爲0、0,以及提供任何動畫轉換。

      2)參數drawingTime:「畫」動做發生的時間點。

       繼續追蹤源碼,進入到以下流程。

 1 //============View.java===========
 2 /**
 3      * This method is called by ViewGroup.drawChild() to have each child view draw itself.
 4      *
 5      * This is where the View specializes rendering behavior based on layer type,
 6      * and hardware acceleration.
 7      */
 8     boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) {
 9       ......
10       draw(canvas);
11       ......
12 }

       註釋中說:該方法被ViewGroup.drawChild()方法調用,來讓每個子view畫它本身。

       該方法中,又回到了draw(canvas)方法中了,而後再開始畫其子view,這樣不斷遞歸下去,直到畫完整棵DecorView樹。

 

  三、DecorView視圖樹的簡易draw流程圖

       針對上述的代碼追蹤流程,這裏梳理了DecorView整個view樹的draw過程的關鍵流程,其中節點比較多,須要耐心分析。

      

       到目前爲止,View的繪製流程就介紹完了。根節點是DecorView,整個View體系就是一棵以DecorView爲根的View樹,依次經過遍從來完成measure、layout和draw過程。而若是要自定義view,通常都是經過重寫onMeasure(),onLayout(),onDraw()來完成要自定義的部分,整個繪製流程也基本上是圍繞着這幾個核心的地方來展開的。

 

8、博文參考閱讀

       【Android View視圖層次

       【Android進階 - 視圖層級實時分析

       【Android視圖繪製流程徹底解析,帶你一步步深刻了解View(二)

       【Android圖形系統(三)-View繪製流程

       【Android View的繪製流程

       【Android View的繪製流程

 

結語

       本文的篇幅比較長,能看完而且理解也是一件辛苦的事情,筆者學習及寫這篇博客,也是花了將近半個月的業餘時間來完成的。可是要想超過別人,就是要作一件有一件辛苦但可以成長的事情,時間長了,人與人之間的距離就拉開了。因此,真心但願本文能幫助您理解View的繪製流程,那筆者半個月來的辛苦也就沒有白費了。固然,本文確定存在不少不足之處,但願讀者能不吝賜教,共同進步。

相關文章
相關標籤/搜索