国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android View 測量流程(Measure)全面解析

2019-12-12 03:42:56
字體:
來源:轉載
供稿:網友

前言

上一篇文章,筆者主要講述了DecorView以及ViewRootImpl相關的作用,這里回顧一下上一章所說的內容:DecorView是視圖的頂級View,我們添加的布局文件是它的一個子布局,而ViewRootImpl則負責渲染視圖,它調用了一個performTraveals方法使得ViewTree開始三大工作流程,然后使得View展現在我們面前。本篇文章主要內容是:詳細講述View的測量(Measure)流程,主要以源碼的形式呈現,源碼均取自Android API 21.

從ViewRootImpl#PerformTraveals說起

我們直接從這個方法說起,因為它是整個工作流程的核心,我們看看它的源碼:

private void performTraversals() {  ... if (!mStopped) {  int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width); // 1  int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);  performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);   } } if (didLayout) {  performLayout(lp, desiredWindowWidth, desiredWindowHeight);  ... } if (!cancelDraw && !newSurface) {  if (!skipDraw || mReportNextDraw) {  if (mPendingTransitions != null && mPendingTransitions.size() > 0) {   for (int i = 0; i < mPendingTransitions.size(); ++i) {   mPendingTransitions.get(i).startChangingAnimations();   }   mPendingTransitions.clear();  }  performDraw();  } }  ...}

方法非常長,這里做了精簡,我們看到它里面主要執行了三個方法,分別是performMeasure、performLayout、performDraw這三個方法,在這三個方法內部又會分別調用measure、layout、draw這三個方法來進行不同的流程。我們先來看看performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)這個方法,它傳入兩個參數,分別是childWidthMeasureSpec和childHeightMeasure,那么這兩個參數代表什么意思呢?要想了解這兩個參數的意思,我們就要先了解MeasureSpec。

理解MeasureSpec

MeasureSpec是View類的一個內部類,我們先看看官方文檔對MeasureSpec類的描述:A MeasureSpec encapsulates the layout requirements passed from parent to child. Each MeasureSpec represents a requirement for either the width or the height. A MeasureSpec is comprised of a size and a mode.它的意思就是說,該類封裝了一個View的規格尺寸,包括View的寬和高的信息,但是要注意,MeasureSpec并不是指View的測量寬高,這是不同的,是根據MeasueSpec而測出測量寬高。
MeasureSpec的作用在于:在Measure流程中,系統會將View的LayoutParams根據父容器所施加的規則轉換成對應的MeasureSpec,然后在onMeasure方法中根據這個MeasureSpec來確定View的測量寬高。
我們來看看這個類的源碼:

public static class MeasureSpec { private static final int MODE_SHIFT = 30; private static final int MODE_MASK = 0x3 << MODE_SHIFT; /**  * UNSPECIFIED 模式:  * 父View不對子View有任何限制,子View需要多大就多大  */  public static final int UNSPECIFIED = 0 << MODE_SHIFT; /**  * EXACTYLY 模式:  * 父View已經測量出子Viwe所需要的精確大小,這時候View的最終大小  * 就是SpecSize所指定的值。對應于match_parent和精確數值這兩種模式  */  public static final int EXACTLY = 1 << MODE_SHIFT; /**  * AT_MOST 模式:  * 子View的最終大小是父View指定的SpecSize值,并且子View的大小不能大于這個值,  * 即對應wrap_content這種模式  */  public static final int AT_MOST = 2 << MODE_SHIFT; //將size和mode打包成一個32位的int型數值 //高2位表示SpecMode,測量模式,低30位表示SpecSize,某種測量模式下的規格大小 public static int makeMeasureSpec(int size, int mode) {  if (sUseBrokenMakeMeasureSpec) {  return size + mode;  } else {  return (size & ~MODE_MASK) | (mode & MODE_MASK);  } } //將32位的MeasureSpec解包,返回SpecMode,測量模式 public static int getMode(int measureSpec) {  return (measureSpec & MODE_MASK); } //將32位的MeasureSpec解包,返回SpecSize,某種測量模式下的規格大小 public static int getSize(int measureSpec) {  return (measureSpec & ~MODE_MASK); } //... }

可以看出,該類的思路是相當清晰的,對于每一個View,包括DecorView,都持有一個MeasureSpec,而該MeasureSpec則保存了該View的尺寸規格。在View的測量流程中,通過makeMeasureSpec來保存寬高信息,在其他流程通過getMode或getSize得到模式和寬高。那么問題來了,上面提到MeasureSpec是LayoutParams和父容器的模式所共同影響的,那么,對于DecorView來說,它已經是頂層view了,沒有父容器,那么它的MeasureSpec怎么來的呢?

為了解決這個疑問,我們回到ViewRootImpl#PerformTraveals方法,看①號代碼處,調用了getRootMeasureSpec(desiredWindowWidth,lp.width)方法,其中desiredWindowWidth就是屏幕的尺寸,并把返回結果賦值給childWidthMeasureSpec成員變量(childHeightMeasureSpec同理),因此childWidthMeasureSpec(childHeightMeasureSpec)應該保存了DecorView的MeasureSpec,那么我們看一下ViewRootImpl#getRootMeasureSpec方法的實現:

/** * @param windowSize *  The available width or height of the window * * @param rootDimension *  The layout params for one dimension (width or height) of the *  window. * * @return The measure spec to use to measure the root view. */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; //省略... } return measureSpec;}

思路也很清晰,根據不同的模式來設置MeasureSpec,如果是LayoutParams.MATCH_PARENT模式,則是窗口的大小,WRAP_CONTENT模式則是大小不確定,但是不能超過窗口的大小等等。

那么到目前為止,就已經獲得了一份DecorView的MeasureSpec,它代表著根View的規格、尺寸,在接下來的measure流程中,就是根據已獲得的根View的MeasureSpec來逐層測量各個子View。我們順著①號代碼往下走,來到performMeasure方法,看看它做了什么工作,ViewRootImpl#performMeasure:

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) { Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure"); try { mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); } finally { Trace.traceEnd(Trace.TRACE_TAG_VIEW); }}

方法很簡單,直接調用了mView.measure,這里的mView就是DecorView,也就是說,從頂級View開始了測量流程,那么我們直接進入measure流程。

measure 測量流程

ViewGroup的測量流程

由于DecorView繼承自FrameLayout,是PhoneWindow的一個內部類,而FrameLayout沒有measure方法,因此調用的是父類View的measure方法,我們直接看它的源碼,View#measure:

public final void measure(int widthMeasureSpec, int heightMeasureSpec) { boolean optical = isLayoutModeOptical(this); if (optical != isLayoutModeOptical(mParent)) { ... if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||  widthMeasureSpec != mOldWidthMeasureSpec ||  heightMeasureSpec != mOldHeightMeasureSpec) {  ...  if (cacheIndex < 0 || sIgnoreMeasureCache) {  // measure ourselves, this should set the measured dimension flag back  onMeasure(widthMeasureSpec, heightMeasureSpec);  mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  }  ...}

可以看到,它在內部調用了onMeasure方法,由于DecorView是FrameLayout子類,因此它實際上調用的是DecorView#onMeasure方法。在該方法內部,主要是進行了一些判斷,這里不展開來看了,到最后會調用到super.onMeasure方法,即FrameLayout#onMeasure方法。

由于不同的ViewGroup有著不同的性質,那么它們的onMeasure必然是不同的,因此這里不可能把所有布局方式的onMeasure方法都分析一遍,因此這里選擇了FrameLayout的onMeasure方法來進行分析,其它的布局方式讀者可以自行分析。那么我們繼續來看看這個方法:

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //獲取當前布局內的子View數量 int count = getChildCount(); //判斷當前布局的寬高是否是match_parent模式或者指定一個精確的大小,如果是則置measureMatchParent為false. final boolean measureMatchParentChildren =  MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||  MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY; mMatchParentChildren.clear(); int maxHeight = 0; int maxWidth = 0; int childState = 0; //遍歷所有類型不為GONE的子View for (int i = 0; i < count; i++) { final View child = getChildAt(i); if (mMeasureAllChildren || child.getVisibility() != GONE) {  //對每一個子View進行測量  measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);  final LayoutParams lp = (LayoutParams) child.getLayoutParams();  //尋找子View中寬高的最大者,因為如果FrameLayout是wrap_content屬性  //那么它的大小取決于子View中的最大者  maxWidth = Math.max(maxWidth,   child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);  maxHeight = Math.max(maxHeight,   child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);  childState = combineMeasuredStates(childState, child.getMeasuredState());  //如果FrameLayout是wrap_content模式,那么往mMatchParentChildren中添加  //寬或者高為match_parent的子View,因為該子View的最終測量大小會受到FrameLayout的最終測量大小影響  if (measureMatchParentChildren) {  if (lp.width == LayoutParams.MATCH_PARENT ||   lp.height == LayoutParams.MATCH_PARENT) {   mMatchParentChildren.add(child);  }  } } } // Account for padding too maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground(); maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground(); // Check against our minimum height and width maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight()); maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth()); // Check against our foreground's minimum height and width final Drawable drawable = getForeground(); if (drawable != null) { maxHeight = Math.max(maxHeight, drawable.getMinimumHeight()); maxWidth = Math.max(maxWidth, drawable.getMinimumWidth()); } //保存測量結果 setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),  resolveSizeAndState(maxHeight, heightMeasureSpec,   childState << MEASURED_HEIGHT_STATE_SHIFT)); //子View中設置為match_parent的個數 count = mMatchParentChildren.size(); //只有FrameLayout的模式為wrap_content的時候才會執行下列語句 if (count > 1) { for (int i = 0; i < count; i++) {  final View child = mMatchParentChildren.get(i);  final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();  //對FrameLayout的寬度規格設置,因為這會影響子View的測量  final int childWidthMeasureSpec;  /**  * 如果子View的寬度是match_parent屬性,那么對當前FrameLayout的MeasureSpec修改:  * 把widthMeasureSpec的寬度規格修改為:總寬度 - padding - margin,這樣做的意思是:  * 對于子Viw來說,如果要match_parent,那么它可以覆蓋的范圍是FrameLayout的測量寬度  * 減去padding和margin后剩下的空間。  *  * 以下兩點的結論,可以查看getChildMeasureSpec()方法:  *  * 如果子View的寬度是一個確定的值,比如50dp,那么FrameLayout的widthMeasureSpec的寬度規格修改為:  * SpecSize為子View的寬度,即50dp,SpecMode為EXACTLY模式  *   * 如果子View的寬度是wrap_content屬性,那么FrameLayout的widthMeasureSpec的寬度規格修改為:  * SpecSize為子View的寬度減去padding減去margin,SpecMode為AT_MOST模式  */  if (lp.width == LayoutParams.MATCH_PARENT) {  final int width = Math.max(0, getMeasuredWidth()   - getPaddingLeftWithForeground() - getPaddingRightWithForeground()   - lp.leftMargin - lp.rightMargin);  childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(   width, MeasureSpec.EXACTLY);  } else {  childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,   getPaddingLeftWithForeground() + getPaddingRightWithForeground() +   lp.leftMargin + lp.rightMargin,   lp.width);  }  //同理對高度進行相同的處理,這里省略...  //對于這部分的子View需要重新進行measure過程  child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } }}

由以上的FrameLayout的onMeasure過程可以看出,它還是做了相當多的工作的,這里簡單總結一下:首先,FrameLayout根據它的MeasureSpec來對每一個子View進行測量,即調用measureChildWithMargin方法,這個方法下面會詳細說明;對于每一個測量完成的子View,會尋找其中最大的寬高,那么FrameLayout的測量寬高會受到這個子View的最大寬高的影響(wrap_content模式),接著調用setMeasureDimension方法,把FrameLayout的測量寬高保存。最后則是特殊情況的處理,即當FrameLayout為wrap_content屬性時,如果其子View是match_parent屬性的話,則要重新設置FrameLayout的測量規格,然后重新對該部分View測量。

在上面提到setMeasureDimension方法,該方法用于保存測量結果,在上面的源碼里面,該方法的參數接收的是resolveSizeAndState方法的返回值,那么我們直接看View#resolveSizeAndState方法:

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

可以看到該方法的思路是相當清晰的,當specMode是EXACTLY時,那么直接返回MeasureSpec里面的寬高規格,作為最終的測量寬高;當specMode時AT_MOST時,那么取MeasureSpec的寬高規格和size的最小值。(注:這里的size,對于FrameLayout來說,是其最大子View的測量寬高)。

小結:那么到目前為止,以DecorView為切入點,把ViewGroup的測量流程詳細地分析了一遍,在ViewRootImpl#performTraversals中獲得DecorView的尺寸,然后在performMeasure方法中開始測量流程,對于不同的layout布局有著不同的實現方式,但大體上是在onMeasure方法中,對每一個子View進行遍歷,根據ViewGroup的MeasureSpec及子View的layoutParams來確定自身的測量寬高,然后最后根據所有子View的測量寬高信息再確定父容器的測量寬高。

那么接下來,我們繼續分析對于一個子View來說,是怎么進行測量的。

View的測量流程

還記得我們上面在FrameLayout測量內提到的measureChildWithMargin方法,它接收的主要參數是子View以及父容器的MeasureSpec,所以它的作用就是對子View進行測量,那么我們直接看這個方法,ViewGroup#measureChildWithMargins:

protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,  mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin   + widthUsed, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,  mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin   + heightUsed, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); // 1}

由源碼可知,里面調用了getChildMeasureSpec方法,把父容器的MeasureSpec以及自身的layoutParams屬性傳遞進去來獲取子View的MeasureSpec,這也印證了“子View的MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同決定”這個結論。那么,我們一起來看看ViewGroup#getChildMeasureSpec方法:

public static int getChildMeasureSpec(int spec, int padding, int childDimension) { int specMode = MeasureSpec.getMode(spec); int specSize = MeasureSpec.getSize(spec); //size表示子View可用空間:父容器尺寸減去padding 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: //省略..具體可自行參考源碼 break; // Parent asked to see how big we want to be case MeasureSpec.UNSPECIFIED: //省略...具體可自行參考源碼 break; } return MeasureSpec.makeMeasureSpec(resultSize, resultMode);}

上面方法也非常容易理解,大概是根據不同的父容器的模式及子View的layoutParams來決定子View的規格尺寸模式等。那么,這里根據上面的邏輯,列出不同的父容器的MeasureSpec和子View的LayoutParams的組合情況下所出現的不同的子View的MeasureSpec:

(注:該表格呈現形式參考自《Android 開發藝術探索》 任玉剛 著)

當子View的MeasureSpec獲得后,我們返回measureChildWithMargins方法,接著就會執行①號代碼:child.measure方法,意味著,繪制流程已經從ViewGroup轉移到子View中了,可以看到傳遞的參數正是我們剛才獲取的子View的MeasureSpec,接著會調用View#measure,這在上面說過了,這里不再贅述,然后在measure方法,會調用onMeasure方法,當然了,對于不同類型的View,其onMeasure方法是不同的,但是對于不同的View,即使是自定義View,我們在重寫的onMeasure方法內,也一定會調用到View#onMeasure方法的,因此我們看看它的源碼:

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

顯然,這里調用了setMeasureDimension方法,上面說過該方法的作用是設置測量寬高,而測量寬高則是從getDefaultSize中獲取,我們繼續看看這個方法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模式,它直接把specSize返回了,即View在這兩種模式下的測量寬高直接取決于specSize規格。也即是說,對于一個直接繼承自View的自定義View來說,它的wrap_content和match_parent屬性的效果是一樣的,因此如果要實現自定義View的wrap_content,則要重寫onMeasure方法,對wrap_content屬性進行處理。
接著,我們看UNSPECIFIED模式,這個模式可能比較少見,一般用于系統內部測量,它直接返回的是size,而不是specSize,那么size從哪里來的呢?再往上看一層,它來自于getSuggestedMinimumWidth()或getSuggestedMinimumHeight(),我們選取其中一個方法,看看源碼,View#getSuggestedMinimumWidth:

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

從以上邏輯可以看出,當View沒有設置背景的時候,返回mMinWidth,該值對應于android:minWidth屬性;如果設置了背景,那么返回mMinWidth和mBackground.getMinimumWidth中的最大值。那么mBackground.getMinimumWidth又是什么呢?其實它代表了背景的原始寬度,比如對于一個Bitmap來說,它的原始寬度就是圖片的尺寸。到此,子View的測量流程也完成了。

總結

這里簡單概括一下整個流程:測量始于DecorView,通過不斷的遍歷子View的measure方法,根據ViewGroup的MeasureSpec及子View的LayoutParams來決定子View的MeasureSpec,進一步獲取子View的測量寬高,然后逐層返回,不斷保存ViewGroup的測量寬高。

從文章開始到現在,View的測量流程已經全部分析完畢,View的measure流程是三大流程中最復雜的一個流程,其中的MeasureSpec貫穿了整個測量流程,占有非常重要的地位,希望讀者仔細體會這個流程,最后希望這篇文章能幫助你對View的測量流程有進一步的了解,謝謝閱讀。

更多閱讀
Android View 布局流程(Layout)完全解析
Android View 繪制流程(Draw) 完全解析

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 松原市| 垣曲县| 临沧市| 石河子市| 板桥市| 依兰县| 嘉荫县| 柏乡县| 湘西| 济阳县| 家居| 仪陇县| 汕尾市| 桦川县| 潜江市| 吕梁市| 吴江市| 漯河市| 鹿邑县| 罗江县| 屯昌县| 越西县| 谢通门县| 五指山市| 吴旗县| 康定县| 团风县| 涿鹿县| 罗甸县| 济阳县| 红原县| 区。| 东港市| 开远市| 旬阳县| 镇安县| 什邡市| 资兴市| 日照市| 保德县| 措美县|