1 public class MyViewGroup extends ViewGroup {
2 private final static String TAG = "MyViewGroup";
3
4 private final static int VIEW_MARGIN=2;
5
6 public MyViewGroup(Context context) {
7 super(context);
8 }
9 @Override
10 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
11 Log.d(TAG, "widthMeasureSpec = "+widthMeasureSpec+" heightMeasureSpec"+heightMeasureSpec);
12
13 for (int index = 0; index < getChildCount(); index++) {
14 final View child = getChildAt(index);
15 // measure
16 child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
17 }
18
19 super.onMeasure(widthMeasureSpec, heightMeasureSpec);
20 }
21
22 @Override
23 protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
24 Log.d(TAG, "changed = "+arg0+" left = "+arg1+" top = "+arg2+" right = "+arg3+" botom = "+arg4);
25 final int count = getChildCount();
26 int row=0;// which row lay you view relative to parent
27 int lengthX=arg1; // right position of child relative to parent
28 int lengthY=arg2; // bottom position of child relative to parent
29 for(int i=0;i<count;i++){
30
31 final View child = this.getChildAt(i);
32 int width = child.getMeasuredWidth();
33 int height = child.getMeasuredHeight();
34 lengthX+=width+VIEW_MARGIN;
35 lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2;
36 //if it can't drawing on a same line , skip to next line
37 if(lengthX>arg3){
38 lengthX=width+VIEW_MARGIN+arg1;
39 row++;
40 lengthY=row*(height+VIEW_MARGIN)+VIEW_MARGIN+height+arg2;
41
42 }
43
44 child.layout(lengthX-width, lengthY-height, lengthX, lengthY);
45 }
46
47 }
48
49 }
這裡有個地方要注意,那就要明白ViewGroup的繪圖流程:ViewGroup繪制包括兩個步驟:1.measure 2.layout
在兩個步驟中分別調用回調函數:1.onMeasure() 2.onLayout()
1.onMeasure() 在這個函數中,ViewGroup會接受childView的請求的大小,然後通過childView的 measure(newWidthMeasureSpec, heightMeasureSpec)函數存儲到childView中,以便childView的getMeasuredWidth() andgetMeasuredHeight() 的值可以被後續工作得到。
2.onLayout() 在這個函數中,ViewGroup會拿到childView的getMeasuredWidth() andgetMeasuredHeight(),用來布局所有的childView。
3.View.MeasureSpec 與 LayoutParams 這兩個類,是ViewGroup與childView協商大小用的。其中,View.MeasureSpec是ViewGroup用來部署 childView用的, LayoutParams是childView告訴ViewGroup 我需要多大的地方。
4.在View 的onMeasure的最後要調用setMeasuredDimension()這個方法存儲View的大小,這個方法決定了當前View的大小。
效果圖: