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

Android 自定義控件(二):從零實現一個流式布局 FlowLayout

編輯:關於 Android 程式設計

什麼是 ViewGroup

在 Android 的視圖樹中,ViewGroup 是所有布局的父類,我們熟悉的 LinearLayout、RelativeLayout、FrameLayout 都由它派生而來。

換句話說,ViewGroup 是所有布局的「源頭」。只要願意繼承它並重寫測量與布局邏輯,就能造出千變萬化的自定義布局。

自定義 ViewGroup 的四個步驟

1. 創建類並繼承 ViewGroup,重寫三個構造方法;
2. 重寫 onMeasure,確定自己與子 View 的尺寸;
3. 定義 LayoutParams 內部類,承載邊距等參數;
4. 重寫 onLayout,決定子 View 的擺放位置——這一步決定了你的布局有什麼特性。

第一步:繼承與構造

public class FlowLayout extends ViewGroup {

    public FlowLayout(Context context) {
        this(context, null);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

第二步:onMeasure(初版)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // 交給系統測量每個子 View
    measureChildren(widthMeasureSpec, heightMeasureSpec);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

第三步:定義 LayoutParams

為了支持子 View 之間的間距,需要自定義一組 LayoutParams:

public static class FlowLayoutParams extends ViewGroup.MarginLayoutParams {
    public FlowLayoutParams(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}

第四步:onLayout —— 核心邏輯

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    int mViewGroupWidth = getMeasuredWidth();  // 每行寬度上限

    int paintX = left;   // 繪製光標的橫坐標
    int paintY = top;    // 繪製光標的縱坐標
    int maxlineHeight = 0;  // 當前行的最大高度

    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        int childViewHeight = childView.getMeasuredHeight();
        int childViewWidth = childView.getMeasuredWidth();
        FlowLayout.FlowLayoutParams params =
                (FlowLayout.FlowLayoutParams) childView.getLayoutParams();

        // 若加上這個子 View 會超出上限,則換行
        if (paintX + childViewWidth + params.rightMargin > mViewGroupWidth) {
            paintX = left;
            paintY = paintY + maxlineHeight + params.topMargin + params.bottomMargin;
            maxlineHeight = 0;
        }

        maxlineHeight = Math.max(childViewHeight, maxlineHeight);

        childView.layout(
                paintX + params.leftMargin,
                paintY + params.topMargin,
                paintX + childViewWidth + params.leftMargin,
                paintY + childViewHeight + params.topMargin);

        // 光標右移
        paintX = paintX + childViewWidth + params.leftMargin + params.rightMargin;
    }
}

逐步拆解思路

1. 記住行寬上限

int mViewGroupWidth = getMeasuredWidth();

2. 用兩個變量記錄繪製起點。子 View 是通過 layout(l, t, r, b) 定位的,每個子 View 的起點都不同,所以必須有游標:

int paintX = left;
int paintY = top;

3. 取出每個子 View 的邊距與尺寸

FlowLayout.FlowLayoutParams params =
        (FlowLayout.FlowLayoutParams) childView.getLayoutParams();
int childViewWidth = childView.getMeasuredWidth();
int childViewHeight = childView.getMeasuredHeight();

4. 判斷是否需要換行。把「當前游標位置 + 這個子 View 的寬度」與行寬上限比較,超了就換行:

paintX = left;
paintY = paintY + maxlineHeight + params.topMargin + params.bottomMargin;
maxlineHeight = childViewHeight;  // 新行的第一個 View,最大高度就是它自己

5. 繪製並移動游標

maxlineHeight = Math.max(childViewHeight, maxlineHeight);
childView.layout(paintX + params.leftMargin,
                 paintY + params.topMargin,
                 paintX + childViewWidth + params.leftMargin,
                 paintY + childViewHeight + params.topMargin);
paintX = paintX + childViewWidth + params.leftMargin + params.rightMargin;

本質上就是:一行一行往右排,放不下就換行,同時記錄每行最高的那個子 View 作為下一行的起始縱坐標。

在布局文件中使用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.view.FlowLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="全部" />
        <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="體育" />
        <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="連續劇" />
        <!-- 其餘按鈕省略 -->
    </com.example.view.FlowLayout>
</RelativeLayout>

運行效果:

達到了預期。但這裡 FlowLayout 的寬高都是 match_parent,如果改成 wrap_content 會怎樣?

把 layout_height 改為 wrap_content 後,屏幕上看起來沒變化,但在預覽窗口中選中 FlowLayout 會發現:它依然是 match_parent 的尺寸,並沒有貼合子 View 的邊緣。

這不是我們想要的。正確行為是:設為 wrap_content 時,FlowLayout 的邊界應該緊緊包住子 View。所以 onMeasure 需要重寫。

完善 onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    // wrap_content 下計算出的最終寬高
    int width = 0;
    int height = 0;
    // 當前行的寬度與高度
    int lineWidth = 0;
    int lineHeight = 0;

    int childCount = getChildCount();
    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        FlowLayout.FlowLayoutParams params =
                (FlowLayout.FlowLayoutParams) childView.getLayoutParams();
        int childWidth = childView.getMeasuredWidth() + params.leftMargin + params.rightMargin;
        int childHeight = childView.getMeasuredHeight() + params.topMargin + params.bottomMargin;

        if (lineWidth + childWidth > widthSize) {
            // 換行:結算上一行
            width = Math.max(width, lineWidth);
            height = height + lineHeight;
            lineWidth = childWidth;
            lineHeight = childHeight;
        } else {
            lineWidth += childWidth;
            lineHeight = Math.max(lineHeight, childHeight);
        }

        // 最後一個子 View 需要單獨結算
        if (i == childCount - 1) {
            width = Math.max(width, lineWidth);
            height += lineHeight;
        }
    }

    // 非 EXACTLY 即說明布局中寫的是 wrap_content
    setMeasuredDimension(
            (widthMode == MeasureSpec.EXACTLY) ? widthSize : width,
            (heightMode == MeasureSpec.EXACTLY) ? heightSize : height);
}

注意循環內必須先調用 measureChildren() 讓子 View 完成測量,否則 getMeasuredWidth() 取到的是 0。上面的代碼裡 super.onMeasure() 之前的 measureChildren 調用需要保留。

再預覽一次

這次 FlowLayout 的邊界已經緊貼子 View 了。

回顧一下:自定義 ViewGroup 的關鍵是 onMeasure 決定「我多大」,onLayout 決定「孩子們站在哪」。兩者配合,才能讓一個自定義布局在 match_parent 和 wrap_content 兩種情況下都表現得符合預期。

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