自定义View画阶梯布局

public class JieTiView extends ViewGroup {
public JieTiView(Context context) {
super(context, null);
}

public JieTiView(Context context, AttributeSet attrs) {
    this(context, attrs, -1);
}

public JieTiView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    //设置个数
    for (int i = 0; i < 5; i++) {
        initView();
    }
}

@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 * (1 + i), measuredHeight * (1 + i));
    }
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.BLUE);
}

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

    int mode = MeasureSpec.getMode(widthMeasureSpec);
    if (mode == MeasureSpec.AT_MOST) {
        int measureWidth = 0;
        int measureHight = 0;
        int resultWidth = 0;
        int resulthight = 0;
        //获取控件个数
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childAt = getChildAt(i);
            //测量控件的宽高
            measureChild(childAt, childAt.getMeasuredWidth(), childAt.getMeasuredHeight());
            measureWidth = childAt.getMeasuredWidth();
            measureHight = childAt.getMeasuredHeight();
            //
            resultWidth += measureWidth;
            resulthight += measureHight;

        }
        setMeasuredDimension(resultWidth, resulthight);
        return;

    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

//设置字体的属性
private TextView initView() {
    TextView textView = new TextView(getContext());
    textView.setBackgroundColor(Color.RED);
    textView.setText("123456");
    textView.setTextSize(20);
    textView.setTextColor(Color.BLACK);
    this.addView(textView);
    return textView;
}

猜你喜欢

转载自blog.csdn.net/zxcce21/article/details/83857943