ViewGroup的测量及绘制方法讲解
扫描二维码
随时随地手机看文章
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过程外,还要遍历去调用所有子元素的measure方法,各子元素再递归去执行这个过程。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()方法都不会被调用。ViewGroup会使用dispatchDraw()方法绘制其子View,过程同样是遍历所有子View,并调用子View的绘制方法来完成绘制。
widthMeasureSpec | heightMeasureSpec |
---|