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

自定義 ViewGroup 實戰:手把手寫一個流式布局 FlowLayout

編輯:關於 Android 程式設計

本文參考並總結了鴻神的 FlowLayout 文章,在此基礎上做了修正,也補充了一些自己的理解,文末附上原文地址。

什麼是流式布局

流式布局(FlowLayout)指的是:把一堆寬高不完全相同的 View 按一定規律依次排列,當一行(或一列)放不下時,自動換到下一行。熱門標簽、搜索熱詞、篩選條件這類場景裡到處都是它。

比如下圖這種尺寸選擇:

上圖中「尺寸大小」這一整塊就是一個 ViewGroup,裡面放著寬度各異的子控件。用現有布局硬湊很難做得優雅,而自定義一個 FlowLayout 就順暢多了。

如果說自定義 View 的核心是 onDraw(),那自定義 ViewGroup 的核心就是 onMeasure() 和 onLayout():前者負責測量所有子控件並算出自己的尺寸,後者負責把子控件擺到正確位置。

一、整體思路

1、每個 ViewGroup 都需要一個 LayoutParams。FlowLayout 目前只需要支持 margin,所以直接用系統的 MarginLayoutParams。
2、onMeasure 中先測量所有 childView,再根據它們的寬高算出自己的寬高(當然,如果父容器傳下來的測量模式不是 AT_MOST,就直接採用父容器給的值)。
3、onLayout 中完成所有 childView 的定位。

二、LayoutParams

因為只需支持 margin,直接複用 MarginLayoutParams,重寫 generateLayoutParams:

@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new MarginLayoutParams(getContext(), attrs);
}

三、onMeasure()

/**
 * 負責設置子控件的測量模式和大小,並根據所有子控件設置自己的寬和高
 */
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    // 父容器為我們設置的測量模式和大小
    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

    // wrap_content 情況下,用這兩個變量記錄自己算出的寬高
    int width = 0;
    int height = 0;

    // 每一行的寬度,width 不斷取最大值
    int lineWidth = 0;
    // 每一行的高度,累加進 height
    int lineHeight = 0;

    int cCount = getChildCount();

    for (int i = 0; i < cCount; i++) {
        View child = getChildAt(i);
        // 測量每一個 child
        measureChild(child, widthMeasureSpec, heightMeasureSpec);

        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        // 當前子控件實際佔據的寬高(含 margin)
        int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

        // 如果加上當前 child 會超出最大寬度,則換行
        if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
            width = Math.max(lineWidth, width);   // 取目前最寬的一行
            lineWidth = childWidth;               // 開啟新行,重新記錄
            height += lineHeight;                 // 高度疊加
            lineHeight = childHeight;             // 新行的高度重新計
        } else {
            lineWidth += childWidth;
            lineHeight = Math.max(lineHeight, childHeight);
        }

        // 如果是最後一個,把當前記錄的寬度和當前 lineWidth 再比較一次
        if (i == cCount - 1) {
            width = Math.max(width, lineWidth);
            height += lineHeight;
        }
    }

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

解釋幾個細節:

先取出父容器傳入的測量模式和尺寸,然後遍歷所有子 View 調用 measureChild() 逐一測量。如果父容器的寬或高是 wrap_content,就用我們自己累加計算的值;否則直接沿用父容器傳入的值。

判斷換行時要減去左右 padding,否則內容會被擠出去。

另外原文在這裡寫的是 width = Math.max(lineWidth, childWidth),這其實有問題:假如第一行最寬、後面逐漸變窄,取到的 width 就不對了。改成 Math.max(lineWidth, width) 才是正確的「歷次行寬的最大值」。

最後一段判斷也別省。計算最後一個控件時,無論有沒有換行,都要么補上「最後一行寬度與歷史最大寬度的比較」,要么補上「最後一行高度的疊加」,否則結果會偏小。

四、onLayout()

/** 存儲所有的 View,按行記錄 */
private List<List<View>> mAllViews = new ArrayList<>();
/** 記錄每一行的最大高度 */
private List<Integer> mLineHeight = new ArrayList<>();

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

    int width = getWidth();
    int lineWidth = 0;
    int lineHeight = 0;

    // 當前行的所有 childView
    List<View> lineViews = new ArrayList<>();

    int cCount = getChildCount();

    for (int i = 0; i < cCount; i++) {
        View child = getChildAt(i);
        MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        int childWidth = child.getMeasuredWidth();
        int childHeight = child.getMeasuredHeight();

        // 需要換行
        if (childWidth + lp.leftMargin + lp.rightMargin + lineWidth
                > width - getPaddingLeft() - getPaddingRight()) {
            mLineHeight.add(lineHeight);   // 記錄上一行的最大高度
            mAllViews.add(lineViews);      // 保存上一行
            lineWidth = 0;                 // 重置行寬
            lineViews = new ArrayList<>(); // 開啟新的一行
        }

        lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
        lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
        lineViews.add(child);
    }

    // 記錄最後一行
    mLineHeight.add(lineHeight);
    mAllViews.add(lineViews);

    int left = getPaddingLeft();
    int top = getPaddingTop();

    // 總行數
    int lineNums = mAllViews.size();

    for (int i = 0; i < lineNums; i++) {
        lineViews = mAllViews.get(i);
        lineHeight = mLineHeight.get(i);

        // 遍歷當前行中的所有 View
        for (int j = 0; j < lineViews.size(); j++) {
            View child = lineViews.get(j);
            if (child.getVisibility() == View.GONE) {
                continue;
            }

            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            int lc = left + lp.leftMargin;
            int tc = top + lp.topMargin;
            int rc = lc + child.getMeasuredWidth();
            int bc = tc + child.getMeasuredHeight();

            child.layout(lc, tc, rc, bc);

            left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
        }

        left = getPaddingLeft();   // 重置 left
        top += lineHeight;         // 移到下一行
    }
}

邏輯梳理:

mAllViews 的每一項是「某一行所有 View 的集合」,mLineHeight 記錄每行的高度。

第一個循環(遍歷所有子 View)負責填充這兩個集合;接著按行數外層遍歷,內層再遍歷該行的每個 childView,算出 left / top / right / bottom 並調用 layout();每做完一行就重置 left、遞增 top。

如果考慮到 padding,除了換行判斷要減去 padding,初始的 left 和 top 也要從 getPaddingLeft() / getPaddingTop() 起算。

還有一個值得糾正的小習慣:這裡用的是 child.getMeasuredWidth(),而不是 child.getWidth()。在這個例子中兩者結果相同,但語義上前者更准确——onLayout 階段正是依賴測量結果進行定位的時候。下圖能直觀看出兩者的差別:

左邊是 getWidth,右邊是 getMeasuredWidth。

五、布局文件

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.mydemo2.MainActivity">

    <com.example.mydemo2.MyFlowLayout
        android:id="@+id/myFlowLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView style="@style/MyFlowLayout_viewStyle" android:text="Hello" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="Android" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="我是FlowLayout" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="一個" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="自定義的ViewGroup" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="Hello" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="Android" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="我是FlowLayout" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="一個" />
        <TextView style="@style/MyFlowLayout_viewStyle" android:text="自定義的ViewGroup" />
    </com.example.mydemo2.MyFlowLayout>
</LinearLayout>

這裡抽出了 style,省掉大量重複屬性,以後要改樣式只改一處即可。

style.xml:

<style name="MyFlowLayout_viewStyle">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_margin">4dp</item>
    <item name="android:background">@drawable/my_textview_bg</item>
    <item name="android:textColor">#ffffff</item>
</style>

背景 drawable:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#7690A5" />
    <corners android:radius="5dp" />
    <padding
        android:bottom="2dp"
        android:left="10dp"
        android:right="10dp"
        android:top="2dp" />
</shape>

六、動態添加 View

實戰中標簽內容往往是後端下發的,寫死在布局裡行不通。這就把布局改成只留一個空的父 ViewGroup,其餘全部動態添加。

在 Activity 的 onCreate 中調用 initView():

private void initView() {
    myFlowLayout = (MyFlowLayout) findViewById(R.id.myFlowLayout);

    LayoutInflater mInflater = LayoutInflater.from(this);
    for (int i = 0; i < str.length; i++) {
        TextView tv = (TextView) mInflater.inflate(R.layout.myview, myFlowLayout, false);
        tv.setText(str[i]);
        tv.setTag(i);
        tv.setOnClickListener(this);
        myFlowLayout.addView(tv);
    }
}

這裡的關鍵是 LayoutInflater,它能把我們的 XML 布局文件轉成 View 對象,是動態添加的基礎。注意 inflate 的第三個參數傳 false,這樣它只負責把 attr(包括 style 和 layout_margin)解析好,並不會真的把 View 掛到父容器上,最後由 addView 完成。

七、添加點擊事件

如果每個 TextView 都要響應點擊,用 setTag() 存下標記,後續靠 tag 區分是哪一個。

@Override
public void onClick(View v) {
    reSetTextBg();
    switch ((int) v.getTag()) {
        case 0:
        case 1:
        case 2:
            v.setBackgroundColor(0xffff0000);
            break;
        default:
            break;
    }
}

// 重置所有標簽的背景
private void reSetTextBg() {
    for (int i = 0; i < str.length; i++) {
        TextView tView = (TextView) myFlowLayout.getChildAt(i);
        tView.setBackground(getResources().getDrawable(R.drawable.my_textview_bg));
    }
}

至此,一個可動態添加、可響應點擊的 FlowLayout 就完成了。有任何問題或更好的想法,歡迎留言交流。

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