1、ViewGroup的測量
?
public abstract class
ViewGroup
extends View
implements ViewManager
ViewParent
java.lang.Object
????
android.view.View
?
????
android.view.ViewGroup
Class Overview
A ViewGroup
is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers.
對于ViewGroup來說除了完成自身的measure過程外,還要遍歷去調(diào)用所有子元素的measure方法,各子元素再遞歸去執(zhí)行這個過程。ViewGroup提供了一個measureChildren方法:
protected voidmeasureChildren (int widthMeasureSpec, int heightMeasureSpec) ?
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.
ParametersThe width requirements for this viewThe 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。
measureChild方法:
protected?void?measureChild(View?child,int?parentWidthMeasureSpec,int?parentHeightMeasureSpec){ final?LayoutParams?lp?=?child.getLayoutParams(); final?int?childWidthMeasureSpec?=?getChildMeasureSpec(parentWidth?-?MeasureSpec,mPaddingLeft?+?mPaddingRight,lp.width); final?int?childHeightMeasureSpec?=?getChildMeasureSpec(parentHeight?-?MeasureSpec,mPaddingTop?+?mPaddingBottom,lp.height); child.measure(childWidthMeasureSpec,?childHeightMeasureSpec); }
measureChild的思想就是取出子元素的LayoutParams,再通過getChildMeasureSpec來獲取子元素的MeasureSpec,接著直接將MeasureSpec傳遞給View的measure方法進行測量。
?
2、ViewGroup的繪制
?
ViewGroup通常情況下不需要繪制,如果不用指定ViewGroup的背景顏色,其onDraw()方法都不會被調(diào)用。ViewGroup會使用dispatchDraw()方法繪制其子View,過程同樣是遍歷所有子View,并調(diào)用子View的繪制方法來完成繪制。
widthMeasureSpec | heightMeasureSpec |
---|