ViewGroup的測(cè)量及繪制方法講解
1、ViewGroup的測(cè)量
?
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.
對(duì)于ViewGroup來(lái)說(shuō)除了完成自身的measure過(guò)程外,還要遍歷去調(diào)用所有子元素的measure方法,各子元素再遞歸去執(zhí)行這個(gè)過(guò)程。ViewGroup提供了一個(gè)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時(shí),會(huì)對(duì)每一個(gè)元素進(jìn)行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,再通過(guò)getChildMeasureSpec來(lái)獲取子元素的MeasureSpec,接著直接將MeasureSpec傳遞給View的measure方法進(jìn)行測(cè)量。
?
2、ViewGroup的繪制
?
ViewGroup通常情況下不需要繪制,如果不用指定ViewGroup的背景顏色,其onDraw()方法都不會(huì)被調(diào)用。ViewGroup會(huì)使用dispatchDraw()方法繪制其子View,過(guò)程同樣是遍歷所有子View,并調(diào)用子View的繪制方法來(lái)完成繪制。
widthMeasureSpec | heightMeasureSpec |
---|