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()
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的大小。
更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11