use onLayout implements LinearLayout in vertical orientation
use onLayout implements LinearLayout in vertical orientation
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class MyLayout extends ViewGroup {
public MyLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
//onMeasure被Android在onLayout之前调用。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//所有子View加起来总的高度和宽度。
int measuredWidth = 0;
int measuredHeight = 0;
int count = getChildCount();
for (int i = 0; i < count; i++) {
View v = this.getChildAt(i);
if (v.getVisibility() != View.GONE) {
this.measureChild(v, widthMeasureSpec, heightMeasureSpec);
measuredWidth = Math.max(measuredWidth, v.getMeasuredWidth());
measuredHeight += v.getMeasuredHeight();
}
}
//仔细检查!不要疏忽掉一些padding的值。
measuredWidth += getPaddingLeft() + getPaddingRight();
measuredHeight += getPaddingTop() + getPaddingBottom();
this.setMeasuredDimension(measuredWidth, measuredHeight);
}
// Android系统在onMeasure之后调用onLayout。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// 在left,top,right,bottom这四个坐标参数“框”出来一个盛放子View的矩形空间,在此空间内一个一个摆放子View。
int count = this.getChildCount();
for (int i = 0; i < count; i++) {
View v = getChildAt(i);
if (v.getVisibility() != View.GONE) {
int childHeight = v.getMeasuredHeight();
//在细分的(left, top, right, top + childHeight)框出来的矩形空间内摆放这一子View。
v.layout(left, top, right, top + childHeight);
//把顶点的锚定位置往下移。
top = top + childHeight;
}
}
}
}
还没有评论,来说两句吧...