1. 程式人生 > >自定義控制元件實現階梯佈局

自定義控制元件實現階梯佈局

在這裡插入圖片描述

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();
    }
}

private TextView initTextChild() {
    TextView textView=new TextView(getContext());
    textView.setBackgroundColor(Color.YELLOW);
    textView.setText("豬頭");
    textView.setTextSize(20);
    textView.setTextColor(Color.BLACK);
    this.addView(textView);
    return textView;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int mode=MeasureSpec.getMode(heightMeasureSpec);
    if (mode==MeasureSpec.AT_MOST){
        int measureWidth=0;
        int measureHeight=0;
        int resultWidth=0;
        int resultHeight=0;
        int childCount=getChildCount();
        for (int i = 0; i <childCount ; i++) {
            View childAt=getChildAt(i);
            measureChild(childAt,childAt.getMeasuredWidth(),childAt.getMeasuredHeight());
            int measuredWidth=childAt.getMeasuredWidth();
            int measuredHeight=childAt.getMeasuredHeight();
            resultWidth+=measuredWidth;
            resultHeight+=measuredHeight;
        }
        setMeasuredDimension(resultWidth,resultHeight);
        return;
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@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 onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.parseColor("#98FB98"));
}
}
在主佈局呼叫控制元件就可以實現了