Android 继承ViewGroup必须重写onMeasure方法和onLayout方法

1.在方法onMeasure中调用setMeasuredDimension方法
setMeasuredDimension(int measuredWidth, int measuredHeight)
在onMeasure(int, int)中,必须调用setMeasuredDimension(int width, int height)来存储测量得到的宽度和高度值,如果没有这么去做会触发异常IllegalStateException。

2.在方法onMeasure中调用孩子的measure方法
measure(int widthMeasureSpec, int heightMeasureSpec)
这个方法用来测量出view的大小。父view使用width参数和height参数来提供constraint信息。实际上,view的测量工作在onMeasure(int, int)方法中完成。因此,只有onMeasure(int, int)方法可以且必须被重写。参数widthMeasureSpec提供view的水平空间的规格说明,参数heightMeasureSpec提供view的垂直空间的规格说明。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);        
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width, height);
        for (int i = 0; i < getChildCount(); i++) {
             getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);
        }
}

3.解析onLayout(boolean, int, int, int, int)方法
onLayout(boolean changed, int l, int t, int r, int b)

调用场景:在view给其孩子设置尺寸和位置时被调用。子view,包括孩子在内,必须重写onLayout(boolean, int, int, int, int)方法,并且调用各自的layout(int, int, int, int)方法。

参数说明:参数changed表示view有新的尺寸或位置;参数l表示相对于父view的Left位置;参数t表示相对于父view的Top位置;参数r表示相对于父view的Right位置;参数b表示相对于父view的Bottom位置。.

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cWidth = 0;
        int cHeight = 0;
        MarginLayoutParams params = null;
        for (int i = 0; i < getChildCount(); i++) {
            View childView = getChildAt(i);
            cWidth = childView.getMeasuredWidth();
            cHeight = childView.getMeasuredHeight();
            params = (MarginLayoutParams) childView.getLayoutParams();

            int cl = 0;
            int ct = 0;
            int cr = 0;
            int cb = 0;
            switch (i) {
            case 0:
                cl = params.leftMargin;
                ct = params.topMargin;
                break;
            case 1:
                cl = getWidth() - cWidth - params.leftMargin - params.rightMargin;
                ct = params.topMargin;
                break;
            case 2:
                cl = params.leftMargin;
                ct = getHeight() - cHeight - params.topMargin - params.bottomMargin;
                break;
            case 3:
                cl = getWidth() - cWidth - params.leftMargin - params.rightMargin;
                ct = getHeight() - cHeight - params.topMargin - params.bottomMargin;
                break;
            }

            cr = cl + cWidth;
            cb = ct + cHeight;

            childView.layout(cl, ct, cr, cb);
        }

    }

你可能感兴趣的:(android,onmeasure)