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

自定義 ViewGroup 實現流式佈局(FlowLayout)

編輯:關於 Android 程式設計

流式佈局的規則很直觀:每一行的高度取本行中最高元素的高度;當一個元素在本行放不下時,直接換到下一行。

效果如下:

實現思路

自定義 ViewGroup 只需要做兩件事:

onMeasure:測量子容器,計算出「如果由我自己排版,需要多少寬高」,再調用 setMeasuredDimension 回報給父容器。
onLayout:把子元素按行分組,再逐行確定每個 child 的 left、top、right、bottom。

兩個方法都需要遍歷子元素並做「行寬是否超標」的判斷,因此邏輯高度相似。

FlowLayoutView 代碼

package com.qf.sxy.customview05.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;

/**
 * 流式佈局:一行放不下就換行
 */
public class FlowLayoutView extends ViewGroup {

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

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

    /**
     * 使用 MarginLayoutParams,
     * 這樣才能讀取到子元素在 XML 中設置的 margin
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

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

        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

        // wrap_content 情況下自己累加的寬高
        int width = 0;
        int height = 0;
        // 當前行的寬與高
        int lineWidth = 0;
        int lineHeight = 0;

        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE) {
                continue;
            }
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            // 本行放不下,換行
            if (lineWidth + childWidth > sizeWidth - getPaddingLeft() - getPaddingRight()) {
                width = Math.max(width, lineWidth);
                lineWidth = childWidth;      // 新行重新計寬
                height += lineHeight;        // 累加上一行的高度
                lineHeight = childHeight;    // 新行重新計高
            } else {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
            }

            // 處理最後一個元素
            if (i == cCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }

        setMeasuredDimension(
                modeWidth == MeasureSpec.EXACTLY ? sizeWidth
                        : width + getPaddingLeft() + getPaddingRight(),
                modeHeight == MeasureSpec.EXACTLY ? sizeHeight
                        : height + getPaddingTop() + getPaddingBottom());
    }

    /** 按行存儲所有子元素 */
    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 lineWidth = 0;
        int lineHeight = 0;
        List<View> lineViews = new ArrayList<>();

        int cCount = getChildCount();
        int maxWidth = getWidth() - getPaddingLeft() - getPaddingRight();

        for (int i = 0; i < cCount; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() == View.GONE) {
                continue;
            }
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            int childHeight = child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;

            if (lineWidth + childWidth > maxWidth) {
                // 換行:把已累積的數據入列
                mLineHeight.add(lineHeight);
                mAllViews.add(lineViews);

                lineWidth = childWidth;
                lineHeight = childHeight;
                lineViews = new ArrayList<>();
                lineViews.add(child);
            } else {
                lineWidth += childWidth;
                lineHeight = Math.max(lineHeight, childHeight);
                lineViews.add(child);
            }

            // 最後一個元素收尾
            if (i == cCount - 1) {
                mLineHeight.add(lineHeight);
                mAllViews.add(lineViews);
            }
        }

        int left = getPaddingLeft();
        int top = getPaddingTop();
        int lineNum = mAllViews.size();

        // 逐行擺放
        for (int i = 0; i < lineNum; i++) {
            lineViews = mAllViews.get(i);
            lineHeight = mLineHeight.get(i);
            left = getPaddingLeft();

            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 = rc + lp.rightMargin;
            }
            top += lineHeight;
        }
    }
}

幾個值得注意的細節:

· 重寫 generateLayoutParams 返回 MarginLayoutParams,否則 XML 中設置的 margin 不生效;
· 換行判斷要把左右 padding 算進可用寬度;
· 循環結束後要單獨處理「最後一個元素」,否則末行會丟失;
· onLayout 可能被子系統多次調用,所以每次開頭都要清空緩存集合。

在 Activity 中使用

public class MainActivity extends AppCompatActivity {

    private FlowLayoutView flowLayoutView;

    private String[] titils = {"sds", "da", "aa", "fff", "gggggg", "hhgghg",
            "jjhhhh", "aa", "fff", "gggggg", "hhgghg", "jjhhhh", "sds", "da",
            "aa", "fff", "gggggg", "sds", "da", "aa", "fff", "gggggg"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        flowLayoutView = (FlowLayoutView) findViewById(R.id.flowLayoutView);

        for (int i = 0; i < titils.length; i++) {
            TextView tv = (TextView) LayoutInflater.from(MainActivity.this)
                    .inflate(R.layout.tv, flowLayoutView, false);
            tv.setText(titils[i]);
            flowLayoutView.addView(tv);
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.qf.sxy.customview05.MainActivity">

    <com.qf.sxy.customview05.widget.FlowLayoutView
        android:id="@+id/flowLayoutView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#444444" />
</RelativeLayout>

tv.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tv_shape"
    android:text="AAA"
    android:textColor="#ff0000" />

tv_shape.xml:

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

這套寫法可以擴展出標簽流、篩選條件欄、關鍵詞輸入等常見場景。若需要行距與列距,只需在 onLayout 中為 top 與 left 追加固定間隔即可。

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