Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

自訂 ViewGroup 實作自動換行版面:掌握 measure 與 layout 兩步流程

問題:讓子 View 自己找位置換行

需要一個版面:子 View 排滿一行就自動掉到下一行。既有的 LinearLayout 做不到這件事,網路上也難找到現成範例,但思路其實很清楚——自訂一個 ViewGroup,在 onLayout 中逐一檢查子 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) {
        for (int index = 0; index < getChildCount(); index++) {
            final View child = getChildAt(index);
            child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        final int count = getChildCount();
        int row = 0;          // 目前是第幾列
        int lengthX = left;   // 子 View 相對於父容器的右緣位置
        int lengthY = top;    // 子 View 相對於父容器的下緣位置

        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 + top;

            // 這一行放不下了,換到下一行
            if (lengthX > right) {
                lengthX = width + VIEW_MARGIN + left;
                row++;
                lengthY = row * (height + VIEW_MARGIN) + VIEW_MARGIN + height + top;
            }

            child.layout(lengthX - width, lengthY - height, lengthX, lengthY);
        }
    }
}

一定要先搞懂的繪圖流程

自訂 ViewGroup 之所以容易寫錯,多半是沒弄清楚它的兩個階段:

  1. measure → 回呼 onMeasure()。ViewGroup 在這裡向每個子 View 索取尺寸,透過 child.measure(widthMeasureSpec, heightMeasureSpec) 把結果存進子 View,之後 getMeasuredWidth() 與 getMeasuredHeight() 才有值可取。
  2. layout → 回呼 onLayout()。ViewGroup 在這裡取出上一步量到的尺寸,決定每個子 View 的最終位置。

父子之間怎麼協商尺寸

View.MeasureSpec 與 LayoutParams 就是這場協商的語言:MeasureSpec 是父容器對子 View 下達的「你最多可以用這麼大」,LayoutParams 則是子 View 回報的「我希望要這麼大」。而在子 View 自己的 onMeasure() 尾端,必須呼叫 setMeasuredDimension() 把尺寸存下來——這個呼叫才真正決定了該 View 的大小,漏掉它就會量到 0。

這份範例的取捨

範例把 MeasureSpec 直接寫成 UNSPECIFIED,等於完全放任子 View 自報尺寸,實作簡單但無視父容器的約束;正式專案裡通常會依 widthMeasureSpec 的 mode 做基本的約束處理。另外範例以固定 VIEW_MARGIN 計算間距,且未處理 changed 為 false 時的重複排版,這些都是可以再打磨的細節。理解 measure / layout 的分工之後,要補上並不難。

Copyright © Linux教程網 All Rights Reserved