1 测量
1.1 View的测量
通过查看源码得知,在View中有一个measure方法,注释写的很清楚:系统在测量一个控件的大小的时候会调用该方法。而实际上measure方法内部调用的onMeasure方法才是真正完成了View的测量工作。因此自定义View只需要重写onMeasure方法,实际上measure方法的修饰符是final,子类无法重写。
需要重写onMeasure方法的原因:View的实际测量大小除了和测量模式有关,还和父容器有关。如果在布局中为View的大小指定wrap_content,则其specMode是AT_MOST模式,对应的用MeasureSpect.getSize获取的实际大小就是父容器当前剩余的空间大小,也就相当于match_parent.这显然不是我们想要的效果。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
widthMeasureSpec和heightMeasureSpec两个参数是父容器传递过来的,是一个32位的int数,由MeasureSpec类合成,高2位代表SpecMode(测量模式),低30位代表SpecSize(测量大小)。MeasureSpec是View的一个静态内部类,实际上是封装了用于测量的一系列数值,参数所代表的是MeasureSpec所代表的int值,而不是其本身,这是一种抽象的思想。MeasureSpec描述了父容器对其子View大小的期望,其具体的判定规则可以在ViewGroup类中的getChildMeasureSpec方法中看到。
onMeasure()具体可以按onMeasure->setMeasuredDimension->getDefaultSize查看源码里面的相关方法:
/**
* Utility to return a default size. Uses the supplied size if the
* MeasureSpec imposed no constraints. Will get larger if allowed
* by the MeasureSpec.
*
* @param size Default size for this view
* @param measureSpec Constraints imposed by the parent
* @return The size this view should be.
*/
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;
}
该方法的第一个参数是通过getSuggestedMiniumWidth获取的控件默认宽度(getSuggestedMiniumHeight同理),它的逻辑是:如果View没有设置背景,那么返回的就是通过android:width指定的值,该值默认为0;如果设置了背景,那么返回的就是minWidth和背景(Drawable)的原始宽度两者中的最大值。实际上,联系之前一个方法,只有测量模式为UNSPECIFIED时才会得到该测量值,一般只有用于系统内部测量的过程。
1.2 ViewGroup的测量
相比View的测量,ViewGroup的测量要麻烦的多,除了要完成自身的measure过程,还要遍历调用所有子元素的measure方法,各个子元素再递归执行该过程。
参照《Android开发艺术探索》,ViewGroup是一个抽象类,并不定义测量的具体过程,也好理解,这个需要各个子类去具体实现,因为不同的ViewGroup子类有不同的布局特性,比如LinearLayout就是横向或纵向排列,RelativeLayout就是元素之间的相对位置排列。这里以FrameLayout为例,因为代码量最少,是五大布局中最简单的。它的特点是所有子元素无法随意被指定位置,除了一些固定的属性如layout_gravity,但作用有限。所有子元素默认摆放在左上角,后添加的元素会遮挡之前添加的。如果FrameLayout的尺寸不是精确的,
其大小由其中最大的子控件决定。measure方法如下:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取子控件个数
int count = getChildCount();
//FrameLayout的宽高测量属性是否至少有一项不是精确的
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
//清空用于存放宽高至少有一项为match_parent的子控件的集合
mMatchParentChildren.clear();
int maxHeight = 0; //最大高度
int maxWidth = 0; //最大宽度
int childState = 0; //子控件的测量状态
for (int i = 0; i < count; i++) {
//遍历获取子控件
final View child = getChildAt(i);
//如果android:measureAllChildren="true"或者子控件不是不可见的(还保留空间)
if (mMeasureAllChildren || child.getVisibility() != GONE) {
//测量子控件去除了当前父容器的上下padding,以及子控件的上下margin后的准确高度
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
//获取子控件的LayoutParams
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//最大宽度取当前的与子控件的测量宽度与左右margin之和的最大值
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
//合并当前子控件与上一个控件的测量状态
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
//将综合了最大尺寸、测量准则和测量状态的值设置给FrameLayout的尺寸
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
//至此FrameLayout的测量已经完成
count = mMatchParentChildren.size();
//满足该条件说明:1.当前FrameLayout的测量模式至少有一项不是精准的,2.至少有一项测量模式为match_parent的子控件的个数>1
//若满足,需要重新测量该集合中的所有子控件
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
final int width = Math.max(0, getMeasuredWidth()
- getPaddingLeftWithForeground() - getPaddingRightWithForeground()
- lp.leftMargin - lp.rightMargin);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
final int childHeightMeasureSpec;
if (lp.height == LayoutParams.MATCH_PARENT) {
final int height = Math.max(0, getMeasuredHeight()
- getPaddingTopWithForeground() - getPaddingBottomWithForeground()
- lp.topMargin - lp.bottomMargin);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
1.3 父容器对于子控件的尺寸限制
LinearLayout和FrameLayout: 子控件可以超过父容器的范围,只是在IDE的布局预览图看不到超出的部分,而代码中可以正常得到测量值
RelativeLayout:子控件不可以超过父容器的范围
不管是View还是ViewGroup,重写了onMeasure方法的时候,一般我们都会调用setMeasuredDimension(width,height)为控件本身设定尺寸 ,width和height我们给传什么值,它在布局中显示出来的就是这么大.ViewGroup递归层层测量,而最终的屏幕布局,也就是最顶层的容器由谁测量呢?实际上手机当前的分辨率和尺寸都已经写在了一个专门的配置文件中了,也就是整个屏幕的尺寸
2 布局
测量好控件的大小后,就要摆放控件的位置。这是View运行机制的第二阶段,父容器会遍历所有子元素并调用其layout方法,完成该方法所需的测量值都是在测量的步骤中得到的.View自身的layout方法会确定一个控件本身的位置,虽然不是final类型的但子类不应该重写,而其内部会调用onLayout方法。View类中的onLayout方法是空的,子类需要看情况是否重写。而ViewGroup类中的onLayout是抽象方法,子类必须实现。
所以完成布局的总体策略就是:自定义的ViewGroup重写onLayout方法,其中需要遍历子View,调用它们的layout方法,让子View自己确定自己的摆放位置。以LinearLayout的竖直排列的布局方法为例:
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
// Where right end of child should go
final int width = right - left;
int childRight = width - mPaddingRight;
// Space available for child
int childSpace = width - paddingLeft - mPaddingRight;
final int count = getVirtualChildCount();
final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
switch (majorGravity) {
case Gravity.BOTTOM:
// mTotalLength contains the padding already
childTop = mPaddingTop + bottom - top - mTotalLength;
break;
// mTotalLength contains the padding already
case Gravity.CENTER_VERTICAL:
childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
break;
case Gravity.TOP:
default:
childTop = mPaddingTop;
break;
}
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
int gravity = lp.gravity;
if (gravity < 0) {
gravity = minorGravity;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / 2)
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = paddingLeft + lp.leftMargin;
break;
}
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
childTop += lp.topMargin;
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
核心思想就是:遍历内部的子控件,并调用setChildFrame方法,内部就是调用了子控件的layout方法摆放位置。最主要的,每一次循环childTop都逐渐增大,这刚好符合LinearLayout竖直排列,后添加的子控件会被摆放在靠下的位置。
3 绘制
经过了测量和布局,知道了尺寸和位置,就要开始具体的绘制了。当然不是所有的控件都需要绘制。
相关的,View类中提供了两个方法:draw和onDraw。draw方法用于手动将该控件和它的所有子控件渲染到指定的画布(canvas)上。按照注释,一般按一下顺序执行:
1.绘制背景,如果有必要:drawBackground
2.绘制自身:onDraw
3.绘制子元素:dispatchDraw
4.绘制装饰,例如前景和滚动条:onDrawForeground
实际上自定义View不应该重写draw方法,类似layout,相反应重写onDraw方法。在View类中的onDraw方法为空,具体怎么画由子类完成。而dispatchDraw方法也为空,但这是给内部子元素的绘制,ViewGroup类复写了此方法,其内部是调用了所有子元素的draw方法,这样draw事件就得以一层层的传递下去。