自定义ViewGroup和其子View

ViewGroup 初始化计算width,height。顺序如下

05-13 13:41:57.649 D/GestureLockFred(32644): onMeasure 
05-13 13:41:57.649 D/GestureLockFred(32644): onMeasure 
05-13 13:41:57.719 D/GestureLockFred(32644): onMeasure 
05-13 13:41:57.719 D/GestureLockFred(32644): onMeasure 
05-13 13:41:57.719 D/GestureLockFred(32644): onSizeChanged
05-13 13:41:57.719 D/GestureLockFred(32644): onLayout

onMeasure获得ViewGroup本身的width,height,可以重新去定义width,height,同时,通过 getChildCount可以获得childview的个数
如果是动态加载childView,需要在这里计算所有的childView的width, height

final int childCount = getChildCount();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, childWidthMode);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, childHeightMode);
for (int i = 0; i < childCount; i++)
{
    View child = getChildAt(i);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

onMeasure之后,ViewGroup的size就确定了, 可以通过onSizeChanged获得ViewGroup真实有效的width和height。所有的坐标都是相对于空间内部的。

protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//    super.onSizeChanged(w, h, oldw, oldh);
    mWidth = w;
    mHeight = h;
    mCenterX = w / 2;
    mCenterY = h / 2;

    mContentSize = mWidth > mHeight ? mHeight : mWidth;
    mHalContentSize = mContentSize / 2;
}

onLayout是最后确定ViewGroup在parentView中占据的位置。如果是动态加载,可以在这一步对多有的childView确定布局。

protected void onLayout(boolean changed, int l, int t, int r, int b) {

    int totalGap = mAdapter.getBlockGapSize() * (depth - 1);
    final int xStart = mCenterX - mHalContentSize;
    final int yStart = mCenterY - mHalContentSize;

    int xStep = xStart;
    int yStep = yStart;

    int childSize = (mContentSize - totalGap) / depth;
    final int childCount = getChildCount();

    for (int i = 0; i < childCount; i++)
    {
        View child = getChildAt(i);
        child.layout(xStep, yStep, xStep + childSize, yStep + childSize);

        if ( i % depth == depth - 1)
        {
            xStep = xStart;
            yStep += childSize + mAdapter.getBlockGapSize();
        } else {
            xStep += childSize + mAdapter.getBlockGapSize();
        }
    }
}

childView在onLayout之后,也布局位置确定,接下来,就是ViewGroup对所有的childView分派draw的任务,直接复写dispatchDraw,所有的childView就会调用ondraw

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值