public class JieTiViewGroup extends ViewGroup {
public JieTiViewGroup(Context context) {
this(context,null);
}
public JieTiViewGroup(Context context, AttributeSet attrs) {
this(context, attrs,-1);
}
public JieTiViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
for (int i = 0; i < 5; i++) {
initTextChild();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childAt = getChildAt(i);
childAt.measure(0,0);
measureChild(childAt,childAt.getMeasuredWidth(),childAt.getMeasuredHeight());
int measuredWidth = childAt.getMeasuredWidth();
int measuredHeight = childAt.getMeasuredHeight();
childAt.layout(measuredWidth*i,measuredHeight*i,measuredWidth*(i+1),measuredHeight*(i+1));
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode==MeasureSpec.AT_MOST) {
int measuredWidth=0;
int measuredHeight=0;
int resultWidth=0;
int resultHeigh=0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View childAt = getChildAt(i);
measureChild(childAt,childAt.getMeasuredWidth(),childAt.getMeasuredHeight());
measuredWidth = childAt.getMeasuredWidth();
measuredHeight = childAt.getMeasuredHeight();
resultWidth+=measuredWidth;
resultHeigh+=measuredHeight;
}
setMeasuredDimension(resultWidth,resultHeigh);
return;
}
super.onMeasure(widthMeasureSpec,heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.YELLOW);
}
private TextView initTextChild(){
TextView textView = new TextView(getContext());
textView.setBackgroundColor(Color.RED);
textView.setText("123456");
textView.setTextSize(20);
textView.setTextColor(Color.BLUE);
this.addView(textView);
return textView;
}