setMeasuredDimension()
測量階段終極方法,在 onMeasure(int widthMeasureSpec, int heightMeasureSpec) 方法中調用,將計算得到的尺寸,傳遞給該方法,測量階段即結束。該方法也是必須要調用的方法,否則會報異常。在我們在自訂視圖的時候,不需要關心系統複雜的 Measure 過程的,只需調用setMeasuredDimension()設定根據 MeasureSpec 計算得到的尺寸即可,你可以參考 ViewPagerIndicator 的onMeasure方法。
下面我們取 ViewGroup 的 measureChildren(int widthMeasureSpec, int heightMeasureSpec) 方法對複合 View 的 Measure 流程做一個分析: MeasureChild 的方法調用流程圖:
源碼分析
/** * 請求所有子 View 去 measure 自己,要考慮的部分有對子 View 的測繪要求 MeasureSpec 以及其自身的 padding * 這裡跳過所有為 GONE 狀態的子 View ,最繁重的工作是在 getChildMeasureSpec 方法中處理的 * * @param widthMeasureSpec 對該 View 的 width 測繪要求 * @param heightMeasureSpec 對該 View 的 height 測繪要求 */ 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); } } } protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) { final LayoutParams lp = child.getLayoutParams();//擷取Child的LayoutParams final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,// 擷取 ChildView的widthMeasureSpec mPaddingLeft + mPaddingRight, lp.width); final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,// 擷取 ChildView的heightMeasureSpec mPaddingTop + mPaddingBottom, lp.height); child.measure(childWidthMeasureSpec, childHeightMeasureSpec); } /** * 該方法是 measureChildren 中最繁重的部分,為每一個 ChildView 計算出自己的 MeasureSpec。 * 目標是將 ChildView 的 MeasureSpec 和 LayoutParams 結合起來去得到一個最合適的結果。 * * @param spec 對該 View 的測繪要求 * @param padding 當前 View 在當前唯獨上的 paddingand,也有可能含有 margins * * @param childDimension 在當前維度上(height或width)的具體指 * @return 子視圖的 MeasureSpec */ public static int getChildMeasureSpec(int spec, int padding, int childDimension) { ......... // 根據擷取到的子視圖的測量要求和大小建立子視圖的MeasureSpec return MeasureSpec.makeMeasureSpec(resultSize, resultMode); } /** * * 用於擷取 View 最終的大小,父視圖提供了寬、高的約束資訊 * 一個 View 的真正的測量工作是在 onMeasure(int, int) 中,由該方法調用。 * 因此,只有 onMeasure(int, int) 可以而且必須被子類複寫 * * @param widthMeasureSpec 在水平方向上,父視圖指定的的 Measure 要求 * @param heightMeasureSpec 在豎直方向上,控制項上父視圖指定的 Measure 要求 * */ public final void measure(int widthMeasureSpec, int heightMeasureSpec) { ... onMeasure(widthMeasureSpec, heightMeasureSpec); ... } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec), getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec)); }
4. layout 相關概念及核心方法首先要明確的是,子視圖的具體位置都是相對於父視圖而言的。View 的 onLayout 方法為空白實現,而 ViewGroup 的 onLayout 為 abstract 的,因此,如果自訂的 View 要繼承 ViewGroup 時,必須實現 onLayout 函數。
在layout過程中,子視圖會調用getMeasuredWidth()和getMeasuredHeight()方法擷取到 measure 過程得到的 mMeasuredWidth 和 mMeasuredHeight,作為自己的 width 和 height。然後調用每一個子視圖的layout(l, t, r, b)函數,來確定每個子視圖在父視圖中的位置。
LinearLayout 的 onLayout 源碼分析
@Override protected void onLayout(boolean changed, int l, int t, int r, int b) { if (mOrientation == VERTICAL) { layoutVertical(l, t, r, b); } else { layoutHorizontal(l, t, r, b); } } /** * 遍曆所有的子 View,為其設定相對父視圖的座標 */ void layoutVertical(int left, int top, int right, int bottom) { for (int i = 0; i < count; i++) { final View child = getVirtualChildAt(i); if (child == null) { childTop += measureNullChild(i); } else if (child.getVisibility() != GONE) {//不需要立即展示的View設定為GONE可加快繪製 final int childWidth = child.getMeasuredWidth();//measure過程確定的Width final int childHeight = child.getMeasuredHeight();//measure過程確定的height ...確定 childLeft、childTop 的值 setChildFrame(child, childLeft, childTop + getLocationOffset(child), childWidth, childHeight); } } } private void setChildFrame(View child, int left, int top, int width, int height) { child.layout(left, top, left + width, top + height); } View.java public void layout(int l, int t, int r, int b) { ... setFrame(l, t, r, b) } /** * 為該子 View 設定相對其父視圖上的座標 */ protected boolean setFrame(int left, int top, int right, int bottom) { ... }
5. 繪製流程相關概念及核心方法先來看下與 draw 過程相關的函數:
View.draw(Canvas canvas): 由於 ViewGroup 並沒有複寫此方法,因此,所有的視圖最終都是調用 View 的 draw 方法進行繪製的。在自訂的視圖中,也不應該複寫該方法,而是複寫 onDraw(Canvas) 方法進行繪製,如果自訂的視圖確實要複寫該方法,那麼請先調用 super.draw(canvas)完成系統的繪製,然後再進行自訂的繪製。
View.onDraw():
View的onDraw(Canvas)預設是空實現,自訂繪製過程需要複寫的方法,繪製自身的內容。
dispatchDraw() 發起對子視圖的繪製。View中預設是空實現,ViewGroup 複寫了dispatchDraw()來對其子視圖進行繪製。該方法我們不用去管,自訂的 ViewGroup 不應該對dispatchDraw()進行複寫。
繪製流程圖
- View.draw(Canvas) 源碼分析
/** * Manually render this view (and all of its children) to the given Canvas. * The view must have already done a full layout before this function is * called. When implementing a view, implement * {@link #onDraw(android.graphics.Canvas)} instead of overriding this method. * If you do need to override this method, call the superclass version. * * @param canvas The Canvas to which the View is rendered. * * 根據給定的 Canvas 自動渲染 View(包括其所有子 View)。在調用該方法之前必須要完成 layout。當你自訂 view 的時候, * 應該去是實現 onDraw(Canvas) 方法,而不是 draw(canvas) 方法。如果你確實需要複寫該方法,請記得先調用父類的方法。 */ public void draw(Canvas canvas) { / * Draw traversal performs several drawing steps which must be executed * in the appropriate order: * * 1. Draw the background if need * 2. If necessary, save the canvas' layers to prepare for fading * 3. Draw view's content * 4. Draw children (dispatchDraw) * 5. If necessary, draw the fading edges and restore layers * 6. Draw decorations (scrollbars for instance) */ // Step 1, draw the background, if needed if (!dirtyOpaque) { drawBackground(canvas); } // skip step 2 & 5 if possible (common case) final int viewFlags = mViewFlags; if (!verticalEdges && !horizontalEdges) { // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); if (mOverlay != null && !mOverlay.isEmpty()) { mOverlay.getOverlayView().dispatchDraw(canvas); } // we're done... return; } // Step 2, save the canvas' layers ... // Step 3, draw the content if (!dirtyOpaque) onDraw(canvas); // Step 4, draw the children dispatchDraw(canvas); // Step 5, draw the fade effect and restore layers // Step 6, draw decorations (scrollbars) onDrawScrollBars(canvas); }
由上面的處理過程,我們也可以得出一些最佳化的小技巧:當不需要繪製 Layer 的時候第二步和第五步會跳過。因此在繪製的時候,能省的 layer 盡可省,可以提高繪製效率
ViewGroup.dispatchDraw() 源碼分析
dispatchDraw(Canvas canvas){... if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {//處理ChildView的動畫 final boolean buildCache = !isHardwareAccelerated(); for (int i = 0; i < childrenCount; i++) { final View child = children[i]; if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {//只繪製 Visible 狀態的布局,因此可以通過延時載入來提高效率 final LayoutParams params = child.getLayoutParams(); attachLayoutAnimationParameters(child, params, i, childrenCount);// 添加布局變化的動畫 bindLayoutAnimation(child);//為Child綁定動畫 if (cache) { child.setDrawingCacheEnabled(true); if (buildCache) { child.buildDrawingCache(true); } } } } final LayoutAnimationController controller = mLayoutAnimationController; if (controller.willOverlap()) { mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE; } controller.start();// 啟動 View 的動畫} // 繪製 ChildView for (int i = 0; i < childrenCount; i++) { int childIndex = customOrder ? getChildDrawingOrder(childrenCount, i) : i; final View child = (preorderedList == null) ? children[childIndex] : preorderedList.get(childIndex); if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) { more |= drawChild(canvas, child, drawingTime); } }...}protected boolean drawChild(Canvas canvas, View child, long drawingTime) { return child.draw(canvas, this, drawingTime);}/** * This method is called by ViewGroup.drawChild() to have each child view draw itself. * This draw() method is an implementation detail and is not intended to be overridden or * to be called from anywhere else other than ViewGroup.drawChild(). */ boolean draw(Canvas canvas, ViewGroup parent, long drawingTime) { ... }
drawChild(canvas, this, drawingTime)
直接調用了 View 的child.draw(canvas, this,drawingTime)方法,文檔中也說明了,除了被ViewGroup.drawChild()方法外,你不應該在其它任何地方去複寫或調用該方法,它屬於 ViewGroup。而View.draw(Canvas)方法是我們自訂控制項中可以複寫的方法,具體可以參考上述對view.draw(Canvas)的說明。從參數中可以看到,child.draw(canvas, this, drawingTime) 肯定是處理了和父視圖相關的邏輯,但 View 的最終繪製,還是View.draw(Canvas)方法。
invalidate()
請求重繪 View 樹,即 draw 過程,假如視圖發生大小沒有變化就不會調用layout()過程,並且只繪製那些調用了invalidate()方法的 View。
requestLayout()
當布局變化的時候,比如方向變化,尺寸的變化,會調用該方法,在自訂的視圖中,如果某些情況下希望重新測量尺寸大小,應該手動去調用該方法,它會觸發measure()和layout()過程,但不會進行 draw。