viewgroup简单说就是可以装view的view.今天遇到一个问题,就是需要一个可以自动根据一行中view的宽度自动换行的布局,网上找了下,没有相关的例子,但是找到了思路:自定义一个viewgroup,然后在onlayout文件里面自动检测view的右边缘的横坐标值,和你的view的parent view的况度判断是否换行显示view就可以了。因为代码比较简单,就不多说了:
public class MyViewGroup extends ViewGroup { private final static String TAG = "MyViewGroup"; private final static int VIEW_MARGIN=2; public MyViewGroup(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { Log.d(TAG, "widthMeasureSpec = "+widthMeasureSpec+" heightMeasureSpec"+heightMeasureSpec); for (int index = 0; index < getChildCount(); index++) { final View child = getChildAt(index); // measure child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) { Log.d(TAG, "changed = "+arg0+" left = "+arg1+" top = "+arg2+" right = "+arg3+" botom = "+arg4); final int count = getChildCount(); int row=0;// which row lay you view relative to parent int lengthX=arg1; // right position of child relative to parent int lengthY=arg2; // bottom position of child relative to parent for(int i=0;i<count;i++){ final View child = this.getChildAt(i); int width = child.getMeasuredWidth(); int height = child.getMeasuredHeight(); lengthX+=width+VIEW_MARGIN; lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2; //if it can't drawing on a same line , skip to next line if(lengthX>arg3){ lengthX=width+VIEW_MARGIN+arg1; row++; lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2; } child.layout(lengthX-width, lengthY-height, lengthX, lengthY); } } }这里有个地方要注意,那就要明白ViewGroup的绘图流程:ViewGroup绘制包括两个步骤:1.measure 2.layout
在两个步骤中分别调用回调函数:1.onMeasure() 2.onLayout()