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

自定義 ViewGroup 實戰:打造標簽流式布局 FlowLayout

編輯:關於 Android 程式設計

做過內容類應用的同學大概都遇過這樣的需求:熱門標簽、用戶自選標籤,控件要從左往右自動排布,一行放不滿就換行。系統並沒有現成的組件,於是我們需要自己動手寫一個 ViewGroup。網上開源的 FlowLayout 不少,但自己實現一遍,才能真正理解自定義 ViewGroup 的測量與布局流程。

一、動手之前先想清楚四件事

1. 什麼是 ViewGroup?顧名思義就是「控件組」,內部裝著一批 View。而 ViewGroup 本身又繼承自 View,這意味著一個 View 既可以是單個控件,也可以是一組控件的集合。

2. 常見的 ViewGroup 有哪些?LinearLayout、RelativeLayout、FrameLayout、AbsoluteLayout、GridLayout、TableLayout,其中前兩者在項目裡出現頻率最高。

3. ViewGroup 的職責是什麼?為每個 childView 計算出建議的寬高與測量模式,然後決定它們各自擺放的位置。

4. 什麼是流式布局?子控件依據父容器的可用寬度從左到右依次排列,當前行放得下就放在當前行,放不下就自動換到下一行的最左側。

二、自定義 ViewGroup 的四步套路

1. 定義自定義屬性;
2. 在構造方法中讀取這些屬性;
3. 重寫 onMeasure;
4. 重寫 onLayout。

三、先認識 ViewGroup 的四個構造函數

FlowLayout(Context context):代碼中直接 new 實例時走這條路。

FlowLayout(Context context, AttributeSet attrs):在 XML 布局文件中聲明時調用,attrs 負責把 XML 裡寫的自定義屬性帶進來。

FlowLayout(Context context, AttributeSet attrs, int defStyleAttr):第三個參數是當前 Theme 下的默認 Style,只有明確指定時才會用到。

FlowLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes):API 21 才新增的版本。

四、定義自定義屬性

在 res/values/ 下新建 attrs.xml:

<resources>
    <declare-styleable name="FlowLayout">
        <!-- 每個 item 的縱向間距 -->
        <attr name="verticalSpacing" format="dimension" />
        <!-- 每個 item 的橫向間距 -->
        <attr name="horizontalSpacing" format="dimension" />
    </declare-styleable>
</resources>

format 用來聲明取值類型,共 10 種:string、color、dimension、integer、enum、reference、float、boolean、fraction、flag。

五、在布局文件中引用

<LinearLayout
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.per.flowlayoutdome.FlowLayout
        android:id="@+id/tcy_hot_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dp"
        custom:horizontalSpacing="6dp"
        custom:verticalSpacing="12dp" />
</LinearLayout>

千萬別忘了引入 xmlns:custom="https://schemas.android.com/apk/res-auto"。Android Studio 支持 res-auto 命名空間,寫自定義屬性時就有代碼提示了。

六、在構造方法中取回屬性

private int mVerticalSpacing;
private int mHorizontalSpacing;

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

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

public FlowLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray a = context.getTheme()
            .obtainStyledAttributes(attrs, R.styleable.FlowLayout, defStyle, 0);
    for (int i = 0; i < a.getIndexCount(); i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case R.styleable.FlowLayout_verticalSpacing:
                mVerticalSpacing = a.getDimensionPixelSize(
                        R.styleable.FlowLayout_verticalSpacing, 5);
                break;
            case R.styleable.FlowLayout_horizontalSpacing:
                mHorizontalSpacing = a.getDimensionPixelSize(
                        R.styleable.FlowLayout_horizontalSpacing, 10);
                break;
        }
    }
    a.recycle();
}

這裡有個容易踩的坑:很多人習慣把低參數構造函數寫成 super(context),這樣一來只有那個構造函數會被執行,自定義屬性永遠讀不到。正確做法是讓所有構造函數一層層 this(...) 串到三參數版本,把屬性讀取集中放在最深處。

七、核心之一:onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);

    int height = 0;
    int lineHeight = 0;
    int childLeft = getPaddingLeft();
    int childTop = getPaddingTop();

    for (int i = 0; i < getChildCount(); i++) {
        View childView = getChildAt(i);
        measureChild(childView, widthMeasureSpec, heightMeasureSpec);

        int childWidth = childView.getMeasuredWidth();
        int childHeight = childView.getMeasuredHeight();
        lineHeight = Math.max(childHeight, lineHeight);

        // 放不下了,換行
        if (childWidth + childLeft + getPaddingRight() > widthSize) {
            childLeft = getPaddingLeft();
            childTop += mVerticalSpacing + lineHeight;
            lineHeight = childHeight;
        } else {
            childLeft += childWidth + mHorizontalSpacing;
        }
    }
    height += childTop + lineHeight + getPaddingBottom();

    setMeasuredDimension(widthSize,
            heightMode == MeasureSpec.EXACTLY ? heightSize : height);
}

思路很清楚:先拿到父容器給的測量模式與尺寸,遍歷所有子 View 逐一 measureChild,用 childLeft 記錄當前行已佔用的橫向位置,用 lineHeight 記錄當前行的最高值。一旦放不下就換行並累加 childTop。最後如果是 EXACTLY 模式就直接採用父容器給定的高度,否則用自己算出來的高度。寬度在這裡默認按 EXACTLY 處理。

八、核心之二:onLayout

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int width = r - l;
    int childLeft = getPaddingLeft();
    int childTop = getPaddingTop();
    int lineHeight = 0;

    for (int i = 0; i < getChildCount(); i++) {
        final View childView = getChildAt(i);
        if (childView.getVisibility() == View.GONE) {
            continue;
        }
        int childWidth = childView.getMeasuredWidth();
        int childHeight = childView.getMeasuredHeight();
        lineHeight = Math.max(childHeight, lineHeight);

        if (childLeft + childWidth + getPaddingRight() > width) {
            childLeft = getPaddingLeft();
            childTop += mVerticalSpacing + lineHeight;
            lineHeight = childHeight;
        }
        childView.layout(childLeft, childTop,
                childLeft + childWidth, childTop + childHeight);
        childLeft += childWidth + mHorizontalSpacing;
    }
}

onLayout 的換行判斷邏輯與 onMeasure 保持一致,只是把「計算」換成了「真正擺放」。

九、幾個必備的 API

getChildAt(int index) 拿到指定下標的子 View;getChildCount() 得到子 View 數量;measureChild(childView, widthMeasureSpec, heightMeasureSpec) 調用子 View 自身的測量邏輯。這三個方法是自定義 ViewGroup 的入門三件套。

十、讓它能像 ListView 一樣用適配器填充

為了讓 FlowLayout 更易擴展,可以借鑑 ListView 的思路,對外暴露 setAdapter 與 setItemClickListener:

public void setAdapter(BaseAdapter adapter) {
    if (mAdapter == null) {
        mAdapter = adapter;
        if (mObserver == null) {
            mObserver = new DataChangeObserver();
            mAdapter.registerDataSetObserver(mObserver);
        }
        drawLayout();
    }
}

private void drawLayout() {
    if (mAdapter == null || mAdapter.getCount() == 0) {
        return;
    }
    removeAllViews();
    for (int i = 0; i < mAdapter.getCount(); i++) {
        View view = mAdapter.getView(i, null, null);
        final int position = i;
        view.setOnClickListener(v -> {
            if (mListener != null) {
                mListener.itemClick(position);
            }
        });
        addView(view);
    }
}

class DataChangeObserver extends DataSetObserver {
    @Override
    public void onChanged() {
        drawLayout();
    }
}

配套寫一個 FlowLayoutAdapter 繼承 BaseAdapter,在 getView 裡 inflate 標簽樣式並用 ViewHolder 複用,數據變化時調 notifyDataSetChanged,FlowLayout 便會自動重排。

十一、樣式與交互的小細節

標簽本體用一個 Button 加 selector 背景,做出圓角與按下態:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#ff76787b" />
            <corners android:radius="5dp" />
            <stroke android:width="1px" android:color="#ffd1d1d1" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#ffffff" />
            <corners android:radius="2.5dp" />
            <stroke android:width="0.5px" android:color="#ffd1d1d1" />
        </shape>
    </item>
</selector>

業務邏輯上還可以加上「最多選 5 個」的限制、重複標簽去重、以及點擊「自定義」彈出一個 Activity 讓用戶自行輸入(記得在 AndroidManifest 中為該 Activity 配置一個透明背景的 dialog 主題,才能呈現彈窗效果)。

結語

把 FlowLayout 拆開來看,難點並不在代碼量,而在於理解「測量—布局」兩段式流程:onMeasure 負責回答「我需要多大」,onLayout 負責回答「孩子們站在哪」。把這兩件事想通,再複雜的自定義 ViewGroup 也都有章可循。

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