public class CustomViewGroup extends ViewGroup {
 
    public static class LayoutParams extends ViewGroup.MarginLayoutParams {
        public LayoutParams(Context c, AttributeSet attrs) {
            super(c, attrs);            
        }       
    }
 
    @Override  
    public LayoutParams generateLayoutParams(AttributeSet attrs) {  
        return new CustomViewGroup.LayoutParams(getContext(), attrs);  
    }
 
}
这样修改之后,我们就可以在onLayout()函数中获取子控件的layout_margin值了,添加了layout_margin的onLayout()函数实现如下所示:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
 
    int mViewGroupWidth  = getMeasuredWidth();  //当前ViewGroup的总宽度
    int mViewGroupHeight = getMeasuredHeight(); //当前ViewGroup的总高度
 
    int mPainterPosX = left; //当前绘图光标横坐标位置
    int mPainterPosY = top;  //当前绘图光标纵坐标位置  
     
    int childCount = getChildCount();        
    for ( int i = 0; i < childCount; i++ ) {
         
        View childView = getChildAt(i);
 
        int width  = childView.getMeasuredWidth();
        int height = childView.getMeasuredHeight();             
 
        CustomViewGroup.LayoutParams margins = (CustomViewGroup.LayoutParams)(childView.getLayoutParams());
         
        //ChildView占用的width  = width+leftMargin+rightMargin
        //ChildView占用的height = height+topMargin+bottomMargin
        //如果剩余的空间不够,则移到下一行开始位置
        if( mPainterPosX + width + margins.leftMargin + margins.rightMargin > mViewGroupWidth ) {               
            mPainterPosX = left; 
            mPainterPosY += height + margins.topMargin + margins.bottomMargin;
        }                    
         
        //执行ChildView的绘制
        childView.layout(mPainterPosX+margins.leftMargin, mPainterPosY+margins.topMargin,mPainterPosX+margins.leftMargin+width, mPainterPosY+margins.topMargin+height);
         
        mPainterPosX += width + margins.leftMargin + margins.rightMargin;
    }       
}
6. 总结
费了好大劲,终于算是把自定义ViewGroup的onLayout()相关知识点讲清楚了,如果有任何疑问欢迎留言或者来信lujun.hust@gmail.com交流,如果喜欢本文欢迎转载,但希望能尊重我的劳动成果,给出本文文链接,谢谢。
最简单的Ubuntu Touch & Android 双系统安装方式
在Nexus上实现Ubuntu和Android 4.4.2 双启动
Ubuntu 14.04 配置 Android SDK 开发环境
64位Ubuntu 11.10下Android开发环境的搭建(JDK+Eclipse+ADT+Android SDK详细)

