Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

13 問 13 答,全面搞懂 Android View 繪製流程

編輯:關於 Android 程式設計

本文透過 13 個問答,帶大家系統性地理解 Android View 的繪製機制,供大家參考。

1. View 的繪製流程分幾步?從哪開始?哪個過程結束後能看到 View?

答:從 ViewRoot 的 performTraversals 開始,經過 measure、layout、draw 三個流程。draw 流程結束後,就能在螢幕上看到 View 了。

2. View 的測量寬高和實際寬高有區別嗎?

答:絕大多數情況下可以認為沒有區別,但有兩種例外。第一,有時 View 會因某些原因被多次測量,那第一次測量的寬高與最終實際寬高不一定相等,不過此時「最後一次測量」的寬高與實際寬高仍是一致的。此外,實際寬高是在 layout 流程中確定的,我們可以在 layout 流程裡把實際寬高寫死成硬編碼,這樣測量寬高與實際寬高就必然不同——雖然這麼做既沒意義也不好。

3. View 的 measureSpec 由誰決定?頂級 View 呢?

答:由 View 自己的 layoutParams 和父容器共同決定自己的 measureSpec。一旦確定了 spec,onMeasure 中就能確定 View 的寬高。

頂級 View 稍微特殊一些,decorView 的測量在 ViewRootImpl 的源碼裡:

 //desire的這2個參數就代表屏幕的寬高, childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth, lp.width); childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); //decorView的measureSpec就是在這裡確定的,其實比普通view的measurespec要簡單的多 //代碼就不分析了 一目了然的東西 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; } 

4. 對於普通 View 來說,它的 measure 過程與父 View 有關嗎?如果有,這個父 View(ViewGroup)扮演了什麼角色?

答:有關。看源碼:

 //對於普通view的measure來說 是由這個view的 父view ,也就是viewgroup來觸發的。 //也就是下面這個measureChildWithMargins方法 protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed) { //第一步 先取得子view的 layoutParams 參數值 final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams(); //然後開始計算子view的spec的值,注意這裡看到 計算的時候除了要用子view的 layoutparams參數以外 //還用到了父view 也就是viewgroup自己的spec的值 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); } //這個算view的spec的方法 看上去一大串 但是真的邏輯非常簡單 就是根據父親viewgroup //的meaurespec 同時還有view自己的params來確定 view自己的measureSpec。 //注意這裡的參數是padding,這個值的含義是 父容器已占用的控件的大小 所以view的Specsize //的值 你們可以看到 是要減去這個padding的值的。總大小-已經用的 =可用的。 很好理解。 //然後就是下面的switch邏輯 要自己梳理清楚。其實也不難,主要是下面幾條原則 //如果view采用固定寬高,也就是寫死的數值那種。那就不管父親的spec的值了,view的spec 就肯定是exactly 並且大小遵循layout參數裡設置的大小。 //如果view的寬高是match_parent ,那麼就要看父容器viewgroup的 spec的值了,如果父view的spec是exactly模式, //那view也肯定是exactly,並且大小就是父容器剩下的空間。如果父容器是at_most模式,那view也是at_most 並且不會超過剩余空間大小 //如果view的寬高是wrap_content, 那就不管父容器的spec了,view的spec一定是at_most 並且不會超過父view 剩余空間的大小。 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; } return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } 

5. View 的 measure 和 onMeasure 有什麼關係?

答:看源碼:

 //view的measure是final 方法 我們子類無法修改的。 public final void measure(int widthMeasureSpec, int heightMeasureSpec) { boolean optical = isLayoutModeOptical(this); if (optical != isLayoutModeOptical(mParent)) { Insets insets = getOpticalInsets(); int oWidth = insets.left + insets.right; int oHeight = insets.top + insets.bottom; widthMeasureSpec = MeasureSpec.adjust(widthMeasureSpec, optical ? -oWidth : oWidth); heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight); } // Suppress sign extension for the low bytes long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL; if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2); if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT || widthMeasureSpec != mOldWidthMeasureSpec || heightMeasureSpec != mOldHeightMeasureSpec) { // first clears the measured dimension flag mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET; resolveRtlPropertiesIfNeeded(); int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 : mMeasureCache.indexOfKey(key); if (cacheIndex < 0 || sIgnoreMeasureCache) { // measure ourselves, this should set the measured dimension flag back onMeasure(widthMeasureSpec, heightMeasureSpec); mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } else { long value = mMeasureCache.valueAt(cacheIndex); // Casting a long to int drops the high 32 bits, no mask needed setMeasuredDimensionRaw((int) (value >> 32), (int) value); mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT; } // flag not set, setMeasuredDimension() was not invoked, we raise // an exception to warn the developer if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) { throw new IllegalStateException("View with id " + getId() + ": " + getClass().getName() + "#onMeasure() did not set the" + " measured dimension by calling" + " setMeasuredDimension()"); } mPrivateFlags |= PFLAG_LAYOUT_REQUIRED; } mOldWidthMeasureSpec = widthMeasureSpec; mOldHeightMeasureSpec = heightMeasureSpec; mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 | (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension } //不過可以看到的是在measure方法裡調用了onMeasure方法 //所以就能知道 我們在自定義view的時候一定是重寫這個方法! protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); } 

6. 簡要分析 View 的 measure 流程?

答:先回顧問題 4,ViewGroup 算出子 View 的 spec 後,會呼叫子 View 的 measure 方法;而問題 5 也看過,子 View 的 measure 實際上是呼叫 onMeasure。所以我們只要分析好 onMeasure 即可。注意 onMeasure 的參數正是父 View 算出來的那兩個 spec 值(此處 measure 方法會對 spec 裡的 specSize 做略微修改,這部分很簡單,就不展開了)。

 //可以看出來這個就是setMeasuredDimension方法的調用 這個方法看名字就知道就是確定view的測量寬高的 //所以我們分析的重點就是看這個getDefaultSize 方法 是怎麼確定view的測量寬高的 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); } //這個方法特別簡單 基本可以認為就是近似的返回spec中的specSize,除非你的specMode是UNSPECIFIED //UNSPECIFIED 這個一般都是系統內部測量才用的到,這種時候返回size 也就是getSuggestedMinimumWidth的返回值 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; } //跟view的背景相關 這裡不多做分析了 protected int getSuggestedMinimumWidth() { return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth()); } 

7. 自定義 View 中,如果 onMeasure 沒有對 wrap_content 做處理會發生什麼?為什麼?怎麼解決?

答:如果沒對 wrap_content 做處理,那即使你在 XML 裡設為 wrap_content,效果也和 match_parent 相同。看問題 4 的分析可知:當自己的 layout 設為 wrap 時,mode 就是 at_most(無論父 View 是什麼 specMode),這種模式下寬高等於 specSize(由 getDefaultSize 分析可知),而這裡的 specSize 顯然就是 parentSize,也就是父容器剩餘的大小——那不就等同於直接設成 match_parent 了嗎?

解決方式是在 onMeasure 裡針對 wrap 做特殊處理,比如指定一個預設寬高,當發現是 wrap_content 時就套用這個預設值。

8. ViewGroup 有 onMeasure 方法嗎?為什麼?

答:沒有,這個方法交給子類自行實作。不同的 ViewGroup 子類布局都不一樣,onMeasure 索性就全部交給它們自己實現了。

9. 為什麼在 Activity 生命週期裡無法獲得測量寬高?有什麼方法可以解決?

答:因為 measure 過程與 Activity 生命週期沒有任何關係,你無法確定在哪個生命週期結束後 View 的 measure 一定走完。可以嘗試以下幾種方法取得 View 的測量寬高。

 //重寫activity的這個方法 public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { int width = tv.getMeasuredWidth(); int height = tv.getMeasuredHeight(); Log.v("burning", "width==" + width); Log.v("burning", "height==" + height); } } 

或者重寫這個方法:

 @Override protected void onStart() { super.onStart(); tv.post(new Runnable() { @Override public void run() { int width = tv.getMeasuredWidth(); int height = tv.getMeasuredHeight(); } }); } 

再或者:

 @Override protected void onStart() { super.onStart(); ViewTreeObserver observer = tv.getViewTreeObserver(); observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { int width = tv.getMeasuredWidth(); int height = tv.getMeasuredHeight(); tv.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } 

10. layout 和 onLayout 方法有什麼區別?

答:layout 是確定本身 View 的位置,而 onLayout 是確定所有子元素的位置。layout 裡透過 setFrame 方法設定本身 View 的四個頂點,這四個位置確定後,自己 View 的位置就固定了;接著呼叫 onLayout 來確定子元素的位置。View 和 ViewGroup 的 onLayout 方法都沒有寫,留給我們自己為子元素布局。

11. draw 方法大概有幾個步驟?

答:一共四個步驟——繪製背景、繪製自己、繪製 children、繪製裝飾。

12. setWillNotDraw 方法有什麼用?

答:這個方法在 View 裡:

 /** * 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 不需要 draw,就可以把它設為 true,讓系統知道這個 View 不必 draw,進而優化執行速度。ViewGroup 通常預設設為 true,因為它多半只負責布局、不負責 draw;而 View 這個標志位預設則是關閉的。

13. 自定義 View 有哪些需要注意的點?

答:主要是要處理 wrap_content 和 padding,否則 XML 那邊設置這兩個屬性就沒用了。另外不要在 View 中使用 handler,因為系統已經提供了 post 方法。如果是繼承自 ViewGroup,在 onMeasure 和 onLayout 裡也要考慮 padding 與 layout 的影響,也就是要計算 specSize。最後,如果 View 的動畫或線程需要停止,可以考慮在 onDetachedFromWindow 裡來做。

針對上述幾點,這裡給出兩個簡單的自定義 View 供參照。先看一個圓形 View:

 package com.example.administrator.motioneventtest; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; /** * Created by Administrator on 2016/2/4. */ public class CircleView extends View { private int mColor = Color.RED; private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private void init() { mPaint.setColor(mColor); } @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); //處理為wrap_content時的情況 if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(200, 200); } else if (widthSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(200, heightSpecSize); } else if (heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(widthSpecSize, 200); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //處理padding的情況 final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); int width = getWidth() - paddingLeft - paddingRight; int height = getHeight() - paddingTop - paddingBottom; int radius = Math.min(width, height) / 2; canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2, radius, mPaint); } public CircleView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public CircleView(Context context) { super(context); init(); } public CircleView(Context context, AttributeSet attrs) { super(context, attrs); init(); } } 

再來一個稍微複雜、涉及自定義 ViewGroup 的範例(主要用來加强对 onMeasure 和 onLayout 的理解)。需求如下:一個水平的 ViewGroup,內部子元素為了簡單,假設它們的寬高都一樣。來寫一個這樣的簡單 ViewGroup:

 package com.example.administrator.motioneventtest; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.ViewGroup; /** * Created by Administrator on 2016/2/4. */ //這裡我們只處理了padding的狀態 沒有處理margin的狀態,子view的margin 對measure和layout的影響 //就留給讀者自己完成了 public class CustomHorizontalLayout extends ViewGroup { //設置默認的控件最小是多少 這裡不提供自定義屬性了 寫死在代碼裡 你們可以自行拓展 final int minHeight = 0; final int minWidth = 0; public CustomHorizontalLayout(Context context) { super(context); } public CustomHorizontalLayout(Context context, AttributeSet attrs) { super(context, attrs); } public CustomHorizontalLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int measureWidth = 0; int measureHeight = 0; final int childCount = getChildCount(); measureChildren(widthMeasureSpec, heightMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); final View childView = getChildAt(0); final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); //沒有子控件 時 我們的寬高要作特殊處理 if (childCount == 0) { //當沒有子控件時,如果長寬有一個為wrap 那麼就讓這個控件以最小的形式展現 //這裡我們最小設置為0 if (widthSpecMode == MeasureSpec.AT_MOST || heightSpecMode == MeasureSpec.AT_MOST) { setMeasuredDimension(minWidth, minHeight); } else { //否則根據我們的layout屬性來 setMeasuredDimension(getLayoutParams().width, getLayoutParams().height); } } else if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) { measureWidth = childView.getMeasuredWidth() * childCount; measureHeight = childView.getMeasuredHeight(); setMeasuredDimension(paddingLeft + measureWidth + paddingRight, paddingTop + measureHeight + paddingBottom); } else if (heightSpecMode == MeasureSpec.AT_MOST) { measureHeight = childView.getMeasuredHeight(); setMeasuredDimension(paddingLeft + paddingRight + widthSpecSize, paddingTop + paddingBottom + measureHeight); } else if (widthSpecMode == MeasureSpec.AT_MOST) { measureWidth = childView.getMeasuredWidth() * childCount; setMeasuredDimension(paddingLeft + paddingRight + measureWidth, paddingTop + paddingBottom + heightSpecSize); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int paddingLeft = getPaddingLeft(); final int paddingRight = getPaddingRight(); final int paddingTop = getPaddingTop(); final int paddingBottom = getPaddingBottom(); //左邊初始位置為0 int childLeft = 0 + paddingLeft; final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { final View childView = getChildAt(i); if (childView.getVisibility() != View.GONE) { final int childWidth = childView.getMeasuredWidth(); childView.layout(childLeft, 0 + paddingTop, childLeft + childWidth, paddingTop + childView.getMeasuredHeight()); childLeft += childWidth; } } } } 

以上就是本文的全部內容,希望對大家的學習有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved