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

自定義 ViewGroup 實作教學:打造會自動換行的標籤容器 LineBreakLayout

編輯:關於 Android 程式設計

前陣子工作比較滿檔,部落格停更了一段時間,剛把手邊的專案收尾,就趕緊回來替自定義控制項系列補上一篇。這次要動手做的是「標籤自動換行」的版面容器——剛好之前有個案子用得到,評估了一下難度不高,就自己刻了一個。

在先前的文章中介紹過自定義 ViewGroup 的基礎觀念與大致步驟,這次就趁這個實用案例,把整套流程走一遍,做出一個真正能放進專案裡使用的容器。

一、先釐清需求

先看成品示意圖:

圖中以紅框標出的部分,就是我們要達成的效果。系統內建的版面容器沒辦法直接做到這種排版:每個標籤的文字長度不一,一行排滿之後要自動換到下一行,標籤之間的上下左右還要留出間距。仔細拆解,這個容器的規格其實就三件事——可變寬度的項目、超出寬度自動換行、項目間距可設定。

每個標籤本身用 TextView 即可,點擊之後要有選中態(邊框與文字變成藍色)。因此容器內部需要維護兩份集合:一份是全部標籤,一份是目前已選取的標籤;同時對外提供兩個自訂屬性。方向清楚,接下來就一步一步實作。

二、定義自訂屬性

在 values/attrs.xml 中宣告兩個屬性:標籤之間的水平間距 LEFT_RIGHT_SPACE,以及行與行之間的間距 ROW_SPACE,接著在 建構子 中把值讀出來。

values/attrs.xml

<resources>
    <declare-styleable name="LineBreakLayout">
        <!-- 標籤之間左右距離 -->
        <attr name="LEFT_RIGHT_SPACE" format="dimension" />
        <!-- 標籤行距 -->
        <attr name="ROW_SPACE" format="dimension" />
    </declare-styleable>
</resources>

版面檔中使用

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

    <com.openxu.lbl.linebreaklayout.LineBreakLayout
        android:id="@+id/lineBreakLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dip"
        openxu:leftAndRightSpace="20dip"
        openxu:rowSpace="10dip" />

</LinearLayout>

colors.xml

<color name="tv_gray">#666666</color>
<color name="tv_blue">#308BE9</color>
<color name="divider_gray">#d9d9d9</color>

標籤背景 drawable/shape_item_lable_bg.xml

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <!-- 選中效果 -->
    <item android:state_selected="true">
        <shape>
            <solid android:color="#ffffff" />
            <stroke android:width="2px" android:color="@color/tv_blue" />
            <corners android:radius="10000dip" />
        </shape>
    </item>
    <!-- 預設效果 -->
    <item>
        <shape>
            <solid android:color="#ffffff" />
            <stroke android:width="2px" android:color="@color/divider_gray" />
            <corners android:radius="10000dip" />
        </shape>
    </item>
</selector>

標籤版面 layout/item_lable.xml

<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_item_lable_bg"
    android:paddingLeft="12dip"
    android:paddingRight="12dip"
    android:paddingTop="5dip"
    android:paddingBottom="5dip"
    android:text="lable"
    android:textColor="@color/tv_gray"
    android:textSize="15sp" />

三、對外開放 setLables() 供外部塞入標籤

容器要能被使用,得先有一個資料入口。這裡設計成可選擇「追加」或「整批替換」,同時在 inflate 每一個標籤時就把選中態與點擊行為綁好。

/**
 * 設定標籤
 * @param lables 標籤集合
 * @param add 是否追加
 */
public void setLables(List<String> lables, boolean add) {
    if (this.lables == null) {
        this.lables = new ArrayList<>();
    }
    if (add) {
        this.lables.addAll(lables);
    } else {
        this.lables.clear();
        this.lables = lables;
    }
    if (lables != null && lables.size() > 0) {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        for (final String lable : lables) {
            final TextView tv = (TextView) inflater.inflate(R.layout.item_lable, null);
            tv.setText(lable);
            // 依集合內容還原選中狀態
            if (lableSelected.contains(lable)) {
                tv.setSelected(true);
                tv.setTextColor(getResources().getColor(R.color.tv_blue));
            } else {
                tv.setSelected(false);
                tv.setTextColor(getResources().getColor(R.color.tv_gray));
            }
            // 點擊時反轉選中態,並同步維護已選集合
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tv.setSelected(tv.isSelected() ? false : true);
                    if (tv.isSelected()) {
                        tv.setTextColor(getResources().getColor(R.color.tv_blue));
                        lableSelected.add(lable);
                    } else {
                        tv.setTextColor(getResources().getColor(R.color.tv_gray));
                        lableSelected.remove(lable);
                    }
                }
            });
            addView(tv);
        }
    }
}

四、覆寫 onMeasure():把容器高度算出來

關於 onMeasure() 的整體觀念,前面已有專文深入解析,這裡只針對本容器的特性補充。寬度直接沿用系統給的建議值(match_parent 或明確 size)即可;真正需要自己算的是高度——它取決於標籤一共佔了幾行。公式很直覺:

高度 = 單一標籤高度 × 行數 + 行距 ×(行數 − 1)

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // 先讓所有子 View 完成自身測量
    measureChildren(widthMeasureSpec, heightMeasureSpec);

    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    // 寬度採用建議值;即使外部寫 wrap_content,這裡也按 match_parent 處理
    int width = MeasureSpec.getSize(widthMeasureSpec);
    int height;

    if (heightMode == MeasureSpec.EXACTLY) {
        // 明確高度(match_parent 或固定值)時直接採用建議值
        height = heightSize;
    } else {
        int childCount = getChildCount();
        if (childCount <= 0) {
            height = 0;
        } else {
            int row = 1;          // 行數
            int widthSpace = width; // 目前這一行右側剩餘可用寬度
            for (int i = 0; i < childCount; i++) {
                View child = getChildAt(i);
                int childW = child.getMeasuredWidth();
                if (widthSpace >= childW) {
                    widthSpace -= childW;
                } else {
                    row++;
                    widthSpace = width - childW;
                }
                // 扣掉標籤之間的水平間距
                widthSpace -= LEFT_RIGHT_SPACE;
            }
            // 所有標籤高度一致,取第一個即可
            int childH = getChildAt(0).getMeasuredHeight();
            height = (childH * row) + ROW_SPACE * (row - 1);
            Log.v(TAG, "總高度:" + height + " 行數:" + row + " 標籤高度:" + childH);
        }
    }
    setMeasuredDimension(width, height);
}

五、覆寫 onLayout():把標籤實際擺上去

onLayout(boolean changed, int l, int t, int r, int b) 是自定義 ViewGroup 時一定要實作的抽象方法,負責替每個子控制項決定座標。四個參數 l、t、r、b 代表本容器扣除 margin 與 padding 後的可用範圍(相對自身),也就是一個約束條件:子 View 若被擺到範圍外,超出部分不會顯示。

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int row = 0;
    int right = 0;   // 標籤相對於容器的右側座標
    int bottom;      // 標籤相對於容器的底部座標

    for (int i = 0; i < getChildCount(); i++) {
        View childView = getChildAt(i);
        int childW = childView.getMeasuredWidth();
        int childH = childView.getMeasuredHeight();

        right += childW;
        bottom = row * (childH + ROW_SPACE) + childH;

        // 超出右邊界就換行
        if (right > (r - LEFT_RIGHT_SPACE)) {
            row++;
            right = childW;
            bottom = row * (childH + ROW_SPACE) + childH;
        }
        Log.d(TAG, "left = " + (right - childW) + " top = " + (bottom - childH)
                + " right = " + right + " bottom = " + bottom);
        childView.layout(right - childW, bottom - childH, right, bottom);
        right += LEFT_RIGHT_SPACE;
    }
}

六、實際跑跑看

容器寫完,來看實際成果。這裡刻意幫版面加上紅色背景,方便一眼確認計算有沒有出錯——可以看到標籤沒有溢出容器,容器的高寬也剛好把所有標籤包住。

List<String> lable = new ArrayList<>();
lable.add("經濟");
lable.add("娛樂");
lable.add("八卦");
lable.add("小道消息");
lable.add("政治中心");
lable.add("彩票");
lable.add("情感");

lineBreakLayout.setLables(lable, true);

// 取得目前被選取的標籤
List<String> selectedLables = lineBreakLayout.getSelectedLables();

執行結果:

七、小結

就技術門檻而言,這個容器並不難,但它非常具有代表性:一個典型的自定義 ViewGroup,把測量、配置、屬性定義、子 View 生成這幾件事完整走過一輪。能把這個範例從頭寫一遍,之後再遇到需要自定義 ViewGroup 的場景,心裡就有底了。

它當然不是完美的——其實就連系統內建的容器也談不上完美。重點是能否覆蓋眼前專案的開發需求。自定義 ViewGroup 還有事件處理等重要主題,後續文章再陸續補上。

原始碼下載:https://github.com/openXu/LineBreakLayout

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