Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從零打造 FlowLayout:自訂 ViewGroup 實作流式版面

編輯:關於 Android 程式設計

本文整理自鴻洋的 FlowLayout 系列文章,並加入自己的實作與驗證。

一、什麼是 FlowLayout

所謂流式版面,就是控制項依據 ViewGroup 的寬度自動往右排列,當前行剩餘空間不足時自動換到下一行。視覺上像是所有元件不斷往左飄,飄滿一行就換行。Android 系統並沒有內建這種版面,但它在某些場景下非常合適——關鍵字標籤、搜尋熱詞列表都是典型例子。

GitHub 上已有現成實作,本文則從無到有走一遍。

二、實作分析

  1. 需要能識別 margin,因此 LayoutParams 選用 MarginLayoutParams。
  2. 在 onMeasure 中計算所有子 View 的寬高,再據此決定自己的寬高(若非 wrap_content,直接採用父容器傳入的值即可)。
  3. 在 onLayout 中為每個子 View 定位。

三、程式碼

版面配置很單純,放幾個 TextView 當測試資料:

<com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <TextView android:text="Welcome" />
    <TextView android:text="IT 工程師" />
    <TextView android:text="學習中" />
    <TextView android:text="戀愛中" />
    <TextView android:text="掙錢中" />
    <TextView android:text="努力中" />
    <TextView android:text="I think I can" />
</com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup>

核心的自訂 ViewGroup:

public class CustomViewGroup extends ViewGroup {

    public CustomViewGroup(Context context) {
        super(context);
    }

    public CustomViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    /** 一、指定 LayoutParams 為 MarginLayoutParams,才能支援 margin */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    /** 二、計算所有子 View 尺寸,並據此設定自己的寬高 */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

        int width = 0;    // 容器寬度
        int height = 0;   // 容器高度
        int lineWidth = 0;  // 當前行累計寬度
        int lineHeight = 0; // 當前行最大高度

        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            View childView = getChildAt(i);
            measureChild(childView, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams mlp = (MarginLayoutParams) childView.getLayoutParams();
            int cWidth = childView.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;
            int cHeight = childView.getMeasuredHeight() + mlp.topMargin + mlp.bottomMargin;

            if (lineWidth + cWidth > sizeWidth) {
                // 放不下,換行
                width = Math.max(lineWidth, cWidth);
                height += lineHeight;
                lineWidth = cWidth;
                lineHeight = cHeight;
            } else {
                lineWidth += cWidth;
                lineHeight = Math.max(lineHeight, cHeight);
            }
            if (i == cCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }

        setMeasuredDimension(
                (widthMode == MeasureSpec.EXACTLY) ? sizeWidth : width,
                (heightMode == MeasureSpec.EXACTLY) ? sizeHeight : height);
    }

    /** 三、為每個子 View 定位 */
    private List<List<View>> allChildViews = new ArrayList<List<View>>(); // 按行分組
    private List<Integer> maxLineHeight = new ArrayList<Integer>();      // 每行最大高度

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        allChildViews.clear();
        maxLineHeight.clear();

        int width = getWidth();
        int lineWidth = 0;
        int lineHeight = 0;
        List<View> lineChildViews = new ArrayList<View>();

        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            View childView = getChildAt(i);
            MarginLayoutParams mlp = (MarginLayoutParams) childView.getLayoutParams();
            int cWidth = childView.getMeasuredWidth();
            int cHeight = childView.getMeasuredHeight();

            if (lineWidth + cWidth + mlp.leftMargin + mlp.rightMargin > width) {
                // 需要換行
                maxLineHeight.add(lineHeight);
                allChildViews.add(lineChildViews);
                lineChildViews = new ArrayList<View>();
                lineWidth = 0;
            } else {
                lineWidth += cWidth + mlp.leftMargin + mlp.rightMargin;
                lineHeight = Math.max(lineHeight, cHeight + mlp.topMargin + mlp.bottomMargin);
                lineChildViews.add(childView);
            }
        }
        // 記錄最後一行
        maxLineHeight.add(lineHeight);
        allChildViews.add(lineChildViews);

        int left = 0;
        int top = 0;
        int lineNums = allChildViews.size();

        for (int i = 0; i < lineNums; i++) {
            lineChildViews = allChildViews.get(i);
            lineHeight = maxLineHeight.get(i);

            for (int j = 0; j < lineChildViews.size(); j++) {
                View childView = lineChildViews.get(j);
                if (childView.getVisibility() == View.GONE) continue;

                MarginLayoutParams mlp = (MarginLayoutParams) childView.getLayoutParams();
                int lc = left + mlp.leftMargin;
                int tc = top + mlp.topMargin;
                int rc = lc + childView.getMeasuredWidth();
                int bc = tc + childView.getMeasuredHeight();
                childView.layout(lc, tc, rc, bc);
                left += childView.getMeasuredWidth() + mlp.leftMargin + mlp.rightMargin;
            }
            left = 0;        // 換行,左座標歸零
            top += lineHeight; // 上座標累加行高
        }
    }
}

寫法上有兩個關鍵細節值得留意。第一,onMeasure 與 onLayout 各自獨立做了一次換行判斷,因為兩者被呼叫的時機不同,onLayout 執行時拿不到 onMeasure 的中間狀態,只能重新分組一次。第二,onLayout 裡刻意用「先分組、再定位」的兩段式寫法,而非一邊遍歷一邊定位——因為定位時需要知道整行的高度,而那是遍歷完當行才能確定的。

四、變化展示

同一個自訂 ViewGroup 換上不同背景與文字顏色,就能做出多種風格的標籤群:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#E1E6F6"
    android:orientation="vertical">

    <com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView android:text="Welcome" />
        <TextView android:text="IT 工程師" />
        <!-- ... -->
    </com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup>

    <com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView android:background="@drawable/flag_02"
            android:text="Welcome" android:textColor="#888888" />
        <!-- ... -->
    </com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup>

    <com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">
        <TextView android:background="@drawable/flag_03"
            android:text="Welcome" android:textColor="#43BBE7" />
        <!-- ... -->
    </com.cctvjiatao.customviewgroupflowlayout.view.CustomViewGroup>
</LinearLayout>

把寬度改成固定值(例如 200dp)當作根節點,還能得到一個「限寬流式容器」的效果,適合放在側邊欄或對話框裡使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved