Android自定义view之onLayout

在Android自定义view中onLayout用于确定子view的布局位置。列如我们需要实现图中布局:

每一个子view都位于上一个view的底部,右侧。实现这样的viewGroup,首先我们需要把绘测出每一个view的宽高,然后再重新进行布局。
代码如下:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //对子view进行宽高进行测量使得子view可以通过getMeasuredWidth()和getMeasuredHeight()获取到绘制的宽高
        for (int index = 0; index < getChildCount(); index++) {
            View childView = getChildAt(index);
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        //遍历所有子view并且进行布局定义
        //从当前viewGroup的左边,顶部开始
        int preRight = left;
        int preBottom = top;
        for (int index = 0; index < getChildCount(); index++) {
            View childView = getChildAt(index);
            int cLeft = preRight;
            int cTop = preBottom;
            int cRight = cLeft + childView.getMeasuredWidth();
            int cBottom = cTop + childView.getMeasuredHeight();
            //设置view的位置,通过两个点确定一个矩形
            childView.layout(cLeft, cTop, cRight, cBottom);
            preRight = cRight;
            preBottom = cBottom;
        }
    }

发表回复

CAPTCHAis initialing...