在继承ViewGroup类时,子类需要重写两个方法,分别是onMeasure,onLayout两个方法。
1、在onMeasure(int, int)中,必须调用setMeasuredDimension(int width, int height)来存储测量得到的宽度和高度值,如果没有这么去做会触发异常
IllegalStateException。
2、onLayout()的调用时机:在view给其孩子设置尺寸和位置时被调用。
3、执行的顺序:onMeasure(int, int)--->onLayout()
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width=mesureWidth(widthMeasureSpec);
int height=mesureHeight(heightMeasureSpec);
//计算viewgroup子控件的大小
measureChildren(width, height);
//设置自定义viewgroup的大小
setMeasuredDimension(width, height);
}
private int mesureWidth(int width){
int result=0;
//模式
int mode=MeasureSpec.getMode(width);
int widthsize=MeasureSpec.getSize(width);
switch (mode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result=widthsize;
break;
default:
break;
}
return result;
}
private int mesureHeight(int height){
int result=0;
//模式
int mode=MeasureSpec.getMode(height);
int heightsize=MeasureSpec.getSize(height);
switch (mode) {
case MeasureSpec.AT_MOST:
case MeasureSpec.EXACTLY:
result=heightsize;
break;
default:
break;
}
return result;
}
/**
* 调用场景:在view给其孩子设置尺寸和位置时被调用*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int appWidth=this.getWidth();
int appHeight=this.getHeight();
/*int chilcount=getChildCount();
View childview=getChildAt(0);
int h=childview.getMeasuredHeight();*/
Log.i("------->", appWidth+"");
Log.i("------->", appHeight+"");
}