有的时候经常看到这样class **** extends ViewGroup{ } 经过在网上的查阅资料 以及自己的学习记录下对ViewGroup的学习。
通常我们需要实现三个步骤: onMeasure onLayout draw
1.onMeasure 计算控件大小 计算VIewGroup的空间大小
onMeasure传入的widthMeasureSpec和heightMeasureSpec不是一般的尺寸数值,而是将模式和尺寸组合在一起的数值。我们需要通过
int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size = MeasureSpec.getSize(widthMeasureSpec)得到尺寸。
mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, MeasureSpec.AT_MOST。
MeasureSpec.EXACTLY是精确尺寸,当我们将控件的layout_width或layout_height指定为具体数值时如andorid:layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸。
MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸。
MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式。
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获取的是ViewGroup的mode和size
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
System.out.println("Width:" + widthMode + "/" + widthSize);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
System.out.println("Height:" + heightMode + "/" + heightSize);
int count = getChildCount();
for (int i = 0; i < count; i ++) {
View view = getChildAt(i);
// int childWidthSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
// int childHeightSpec = MeasureSpec.makeMeasureSpec(48, MeasureSpec.EXACTLY);
// view.measure(childWidthSpec, childHeightSpec);
this.measureChild(view, widthMeasureSpec, heightMeasureSpec);
}
setMeasuredDimension(widthSize, heightSize);
}
2.onLayout 把每个控件布局到ViewGroup中
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int widthSpan = 0;
int heightSpan = 0;
for (int i = 0; i < count; i ++) {
View child = getChildAt(i);
child.layout(widthSpan, heightSpan, widthSpan + child.getMeasuredWidth(), heightSpan + child.getMeasuredHeight());
widthSpan += child.getMeasuredWidth() + 10;
// heightSpan += child.getMeasuredHeight();
}
}
3. draw
从网上找到的资料解释说Android已经为我们封装好了绘图过程,事故这些方法可不用写。
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}
完成之后就是ViewGroup的简单记录 待改天认真深入研究 献上demo运行效果图。