View 的工作流程主要是指 measure、layout、draw 這三大流程,即測量、布局和繪制,其中 measure 確定 View 的測量寬/高,layout 確定 View 的最終寬/高和四個頂點的位置,而 draw 則將View繪制到屏幕上。
measure 的過程
measure過程要分情況來看,如果只是一個原始的View,那么通過measure方法就完成了其測量過程,如果是一個ViewGroup,除了完成自己的測量過程外,還會遍歷去調用所有子元素的measure方法,各個子元素再遞歸去執行這個流程,下面針對這兩種情況分別討論。
- View的measure過程View的measure過程由其measure方法來完成,measure方法是一個final類型的方法,這意味著子類不能重寫此方法,在View的measure方法中會去調用View的onMeasure方法,因此只需要看onMeasure的實現即可,View的onMeasure方法如下所示。
/**
* Measure the view and its content to determine the measured width and the
* measured height. This method is invoked by {@link #measure(int, int)} and
* should be overridden by subclasses to provide accurate and efficient
* measurement of their contents.
* </p>
*
* <p>
* If this method is overridden, it is the subclass's responsibility to make
* sure the measured height and width are at least the view's minimum height
* and width ({@link #getSuggestedMinimumHeight()} and
* {@link #getSuggestedMinimumWidth()}).
* </p>
*
* @param widthMeasureSpec horizontal space requirements as imposed by the parent.
* The requirements are encoded with
* {@link android.view.View.MeasureSpec}.
* @param heightMeasureSpec vertical space requirements as imposed by the parent.
* The requirements are encoded with
* {@link android.view.View.MeasureSpec}.
*
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension方法會設置View寬/高的測量值,因此我們只需要看View.getDefaultSize這個靜態方法即可:
/**
* Utility to return a default size. Uses the supplied size if the
* MeasureSpec imposed no constraints. Will get larger if allowed
* by the MeasureSpec.
*
* @param size Default size for this view
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
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;
}
可以看出,getDefaultSize這個方法的邏輯很簡單,對于我們來說,我們只需要看AT_MOST和.EXACTLY這兩種情況。簡單地理解,其實getDefaultSize返回的大小就是measureSpec中的specSize,而這個specSize就是View測量后的大小,這里多次提到測量后的大小,是因為View最終的大小是在layout階段確定的,所以這里必須要加以區分,但是幾乎所有情況下View的測量大小和最終大小是相等的。
至于UNSPECIFIED這種情況,一般用于系統內部的測量過程,在這種情況下,View的大小為getDefaultSize的第一個參數size,即寬/高分別為getSuggestedMinimumWidth和getSuggestedMinimumHeight這兩個方法的返回值,看一下它們的源碼:
/**
* Returns the suggested minimum width that the view should use. This
* returns the maximum of the view's minimum width
* and the background's minimum width
* ({@link android.graphics.drawable.Drawable#getMinimumWidth()}).
* <p>
* When being used in {@link #onMeasure(int, int)}, the caller should still
* ensure the returned width is within the requirements of the parent.
*
* @return The suggested minimum width of the view.
*/
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
這里只分析getSuggestedMinimumWidth方法的實現,getSuggestedMinimumHeight和它的實現原理是一樣的。從getSuggestedMinimumWidth的代碼可以看出,如果View沒有設置背景,那么View的寬度為mMinWidth,而mMinWidth對應于android:minWidth這個屬性所指定的值,因此View的寬度即為android:minWidth屬性所指定的值。這個屬性如果不指定,那么mMinWidth則默認為0;如果View指定了背景,則View的寬度為max(mMinWidth,mBackground.getMinimumWidth())。mMinWidth的含義我們已經知道了,那么mBackground.getMinimumWidth()是什么呢?我們看一下Drawable的getMinimumWidth方法,如下所示。
public abstract class Drawable {
...
/**
* Returns the minimum width suggested by this Drawable. If a View uses this
* Drawable as a background, it is suggested that the View use at least this
* value for its width. (There will be some scenarios where this will not be
* possible.) This value should INCLUDE any padding.
*
* @return The minimum width suggested by this Drawable. If this Drawable
* doesn't have a suggested minimum width, 0 is returned.
*/
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
...
}
可以看出,getMinimumWidth返回的就是Drawable的原始寬度,前提是這個Drawable有原始寬度,否則就返回0。那么Drawable在什么情況下有原始寬度呢?這里先舉個例子說明一下,ShapeDrawable無原始寬/高,而BitmapDrawable有原始寬/高(圖片的尺寸),詳細內容會在第6章進行介紹。
這里再總結一下getSuggestedMinimumWidth的邏輯:如果View沒有設置背景,那么返回android:minWidth這個屬性所指定的值,這個值可以為0;如果View設置了背景,則返回android:minWidth和背景的最小寬度這兩者中的最大值,getSuggestedMinimumWidth和getSuggestedMinimumHeight的返回值就是View在UNSPECIFIED情況下的測量寬/高。
從getDefaultSize方法的實現來看,View的寬/高由specSize決定,所以我們可以得出如下結論:直接繼承View的自定義控件需要重寫onMeasure
方法并設置wrap_content時的自身大小,否則在布局中使用wrap_content就相當于使用match_parent。為什么呢?這個原因需要結合上述代碼和表1才能更好地理解。從上述代碼中我們知道,如果View在布局中使用wrap_content,那么它的specMode是AT_MOST模式,在這種模式下,它的寬/高等于specSize;查表4-1可知,這種情況下View的specSize是parentSize,而parentSize是父容器中目前可以使用的大小,也就是父容器當前剩余的空間大小。很顯然,View的寬/高就等于父容器當前剩余的空間大小,這種效果和在布局中使用match_parent完全一致。如何解決這個問題呢?也很簡單,代碼如下所示。
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,mHeight);
} else if (widthSpecMode == AT_MOST) {
setMeasureDimension(mWidth,heightSpecSize);
} else if (heightSpecMode == AT_MOST){
setMeasureDimension(widthSpecSize,mHeight);
}
}
在上面的代碼中,我們只需要給View指定一個默認的內部寬/高(mWidth和mHeight),并在wrap_content時設置此寬/高即可。對于非wrap_content情形,我們沿用系統的測量值即可,至于這個默認的內部寬/高的大小如何指定,這個沒有固定的依據,根據需要靈活指定即可。如果查看TextView、ImageView等的源碼就可以知道,針對wrap_content情形,它們的onMeasure方法均做了特殊處理,讀者可以自行查看它們的源碼。
2. ViewGroup的measure過程
對于ViewGroup來說,除了完成自己的measure過程以外,還會遍歷去調用所有子元素的measure方法,各個子元素再遞歸去執行這個過程。和View不同的是,ViewGroup是一個抽象類,因此它沒有重寫View的onMeasure方法,但是它提供了一個叫measureChildren
的方法,如下所示。
/**
* Ask all of the children of this view to measure themselves, taking into
* account both the MeasureSpec requirements for this view and its padding.
* We skip children that are in the GONE state The heavy lifting is done in
* getChildMeasureSpec.
*
* @param widthMeasureSpec The width requirements for this view
* @param heightMeasureSpec The height requirements for this view
*/
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,ViewGroup.measureChild這個方法的實現也很好理解,如下所示。
/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding.
* The heavy lifting is done in getChildMeasureSpec.
*
* @param child The child to measure
* @param parentWidthMeasureSpec The width requirements for this view
* @param parentHeightMeasureSpec The height requirements for this view
*/
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方法來進行測量。getChildMeasureSpec的工作過程已經在上面進行了詳細分析,通過表1
可以更清楚地了解它的邏輯。我們知道,ViewGroup并沒有定義其測量的具體過程,這是因為ViewGroup是一個抽象類,其測量過程的onMeasure方法需要各個子類去具體實現,比如LinearLayout、RelativeLayout等,為什么ViewGroup不像View一樣對其onMeasure方法做統一的實現呢?那是因為不同的ViewGroup子類有不同的布局特性,這導致它們的測量細節各不相同,比如LinearLayout和RelativeLayout這兩者的布局特性顯然不同,因此ViewGroup無法做統一實現。下面就通過LinearLayout的onMeasure方法來分析ViewGroup的measure過程,其他Layout類型讀者可以自行分析。
首先來看LinearLayout的onMeasure方法,如下所示。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
上述代碼很簡單,我們選擇一個來看一下,比如選擇查看豎直布局的LinearLayout的測量過程,即measureVertical方法,measureVertical的源碼比較長,下面只描述其大概邏輯,首先看一段代碼:
從上面這段代碼可以看出,系統會遍歷子元素并對每個子元素執行measureChildBeforeLayout方法,這個方法內部會調用子元素的measure方法,這樣各個子元素就開始依次進入measure過程,并且系統會通過mTotalLength這個變量來存儲LinearLayout在豎直方向的初步高度。每測量一個子元素,mTotalLength就會增加,增加的部分主要包括了子元素的高度以及子元素在豎直方向上的margin等。當子元素測量完畢后,LinearLayout會測量自己的大小,源碼如下所示。
// Add in our padding
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
// Check against our minimum height
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// Reconcile our calculated size with the heightMeasureSpec
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
...
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
這里對上述代碼進行說明,當子元素測量完畢后,LinearLayout會根據子元素的情況來測量自己的大小。針對豎直的LinearLayout而言,它在水平方向的測量過程遵循View的測量過程,在豎直方向的測量過程則和View有所不同。具體來說是指,如果它的布局中高度采用的是match_parent或者具體數值,那么它的測量過程和View一致,即高度為specSize;如果它的布局中高度采用的是wrap_content,那么它的高度是所有子元素所占用的高度總和,但是仍然不能超過它的父容器的剩余空間,當然它的最終高度還需要考慮其在豎直方向的padding,這個過程可以進一步參看如下源碼:
/**
* Utility to reconcile a desired size and state, with constraints imposed
* by a MeasureSpec. Will take the desired size, unless a different size
* is imposed by the constraints. The returned value is a compound integer,
* with the resolved size in the {@link #MEASURED_SIZE_MASK} bits and
* optionally the bit {@link #MEASURED_STATE_TOO_SMALL} set if the
* resulting size is smaller than the size the view wants to be.
*
* @param size How big the view wants to be.
* @param measureSpec Constraints imposed by the parent.
* @param childMeasuredState Size information bit mask for the view's
* children.
* @return Size information bit mask as defined by
* {@link #MEASURED_SIZE_MASK} and
* {@link #MEASURED_STATE_TOO_SMALL}.
*/
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完成以后,通過getMeasuredWidth/Height方法就可以正確地獲取到View的測量寬/高。需要注意的是,在某些極端情況下,系統可能需要多次measure才能確定最終的測量寬/高,在這種情形下,在onMeasure方法中拿到的測量寬/高很可能是不準確的。一個比較好的習慣是在onLayout方法中去獲取View的測量寬/高或者最終寬/高。
上面已經對View的measure過程進行了詳細的分析,現在考慮一種情況,比如我們想在Activity已啟動的時候就做一件任務,但是這一件任務需要獲取某個View的寬/高。讀者可能會說,這很簡單啊,在onCreate或者onResume里面去獲取這個View的寬/高不就行了?讀者可以自行試一下,實際上在onCreate、onStart、onResume中均無法正確得到某個View的寬/高信息,這是因為View的measure過程和Activity的生命周期方法不是同步執行的,因此無法保證Activity執行了onCreate、onStart、onResume時某個View已經測量完畢了,如果View還沒有測量完畢,那么獲得的寬/高就是0。有沒有什么方法能解決這個問題呢?答案是有的,這里給出四種方法來解決這個問題:
- Activity/View#
onWindowFocusChanged
。onWindowFocusChanged
這個方法的含義是:View已經初始化完畢了,寬/高已經準備好了,這個時候去獲取寬/高是沒問題的。需要注意的是,onWindowFocusChanged會被調用多次,當Activity的窗口得到焦點和失去焦點時均會被調用一次。具體來說,當Activity繼續執行和暫停執行時,onWindowFocusChanged均會被調用,如果頻繁地進行onResume
和onPause
,那么onWindowFocusChanged
也會被頻繁地調用。典型代碼如下:
public void onWindowFocusChanged(boolean hasFocus){
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = view.getMeasureWidth();
int height = view.getMeasureHeight();
}
}
- view.post(runnable)
通過post可以將一個runnable投遞到消息隊列的尾部,然后等待Looper調用此runnable的時候,View也已經初始化好了。典型代碼如下:
protected void onStart(){
super.onStart();
view.post(new Runnable(){
@override
public void run(){
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
- ViewTreeObserver。使用 ViewTreeObserver 的眾多回調可以完成這個功能,比如使用OnGlobalLayoutListener這個接口,當View樹的狀態發生改變或者View樹內部的View的可見性發現改變時,onGlobalLayout 方法將被回調,因此這是獲取View的寬/高一個很好的時機。需要注意的是,伴隨著View樹的狀態改變等,onGlobalLayout會被調用多次。典型代碼如下:
protected void onStart(){
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
@SuppressWarnings("deprecation");
@override
public void onGlobalLayout(){
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
- view.measure(int widthMeasureSpec,int heightMea-sureSpec)。通過手動對View進行measure來得到View的寬/高。這種方法比較復雜,這里要分情況處理,根據View的LayoutParams來分:
- match_parent直接放棄,無法measure出具體的寬/高。原因很簡單,根據View的measure過程,如表1所示,構造此種MeasureSpec需要知道parentSize,即父容器的剩余空間,而這個時候我們無法知道parentSize的大小,所以理論上不可能測量出View的大小。
- 具體的數值(dp/px)比如寬/高都是100px,如下measure:
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec(100, View.MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
- wrap_content如下measure:
int widthMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
int heightMeasureSpec = View.MeasureSpec.makeMeasureSpec((1<<30)-1, View.MeasureSpec.AT_MOST);
v_view1.measure(widthMeasureSpec, heightMeasureSpec);
注意到(1 << 30)-1,通過分析MeasureSpec的實現可以知道,View的尺寸使用30位二進制表示,也就是說最大是30個1(即2^30 – 1),也就是(1 << 30) – 1,在最大化模式下,我們用View理論上能支持的最大值去構造MeasureSpec是合理的。
關于View的measure,網絡上有兩個錯誤的用法。為什么說是錯誤的,首先其違背了系統的內部實現規范(因為無法通過錯誤的MeasureSpec去得出合法的SpecMode,從而導致measure過程出錯),其次不能保證一定能measure出正確的結果。
- 第一種錯誤用法:
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(-1, MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(-1, MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
- 第二種錯誤用法
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
layout 的過程
Layout 的作用是ViewGroup用來確定子元素的位置,當ViewGroup的位置被確定后,它在onLayout中會遍歷所有的子元素并調用其layout方法,在layout方法中onLayout方法又會被調用。Layout過程和measure過程相比就簡單多了,layout方法確定View本身的位置,而onLayout方法則會確定所有子元素的位置,先看View的layout方法。
draw 的過程
Draw過程就比較簡單了,它的作用是將View繪制到屏幕上面。View的繪制過程遵循如下幾步:
- 繪制背景background.draw(canvas)。
- 繪制自己(onDraw)。
- 繪制children(dispatchDraw)。
- 繪制裝飾(onDrawScrollBars)。
這一點通過draw方法的源碼可以明顯看出來,如下所示。
參考書目
- 《android開發藝術探索》任玉剛著