編輯:關於 Android 程式設計
很多 app 裡都有那種「標籤雲」——一串膠囊狀的文字標籤,會自動換行、自動適應螢幕寬度。它看起來像 LinearLayout,但 LinearLayout 不會換行;看起來像 GridView,但每個格子的寬度並不一致。系統沒有現成控制項能滿足,所以我們自己寫一個 ViewGroup。
以下是實機擷取的參考範例(MIUI 8 系統):

以及本文實作的效果:

這個控制項本質是一個容器,需要自己決定子元件怎麼排——因此繼承 ViewGroup 並覆寫 onMeasure 與 onLayout。
這裡有兩個實作上最容易忽略的細節:自訂 View 時必須把自身的 Padding 納入計算;而在自訂 ViewGroup 的 onLayout 中必須把子元件的 Margin 納入計算,否則使用者設定的 margin 會完全失效。
整體繪製流程值得先理解:最上層的 ViewRoot 執行 performTraversals(),接著逐層進行測量、佈局、繪製。父視圖測量時會呼叫子視圖的測量方法,子視圖再呼叫孫視圖,一路遞迴到葉節點——這就是為什麼 onMeasure 裡必須主動呼叫 measureChild(),否則子元件根本不會被測量。
這個控制項的使用方式很像 ListView:透過 setAdapter() 塞入內容,資料變了呼叫 notifyDataSetChanged() 刷新。要模仿它,得先理解 ListView 是怎麼做到這件事的——它用的是典型的觀察者模式。
Adapter 內部的 notifyDataSetChanged():
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
ListView 的 setAdapter()(節錄):
@Override
public void setAdapter(ListAdapter adapter) {
// 每次換新的 adapter 前,先解除對舊 adapter 的監聽
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
resetList();
mRecycler.clear();
...
if (mAdapter != null) {
mItemCount = mAdapter.getCount();
checkFocus();
// 關鍵:向 adapter 註冊一個 Observer
mDataSetObserver = new AdapterDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
...
}
requestLayout();
}
AdapterView 內部的觀察者類別:
class AdapterDataSetObserver extends DataSetObserver {
private Parcelable mInstanceState = null;
@Override
public void onChanged() {
// 資料改變:重新請求佈局
checkFocus();
requestLayout();
}
@Override
public void onInvalidated() {
checkFocus();
requestLayout();
}
public void clearSavedState() {
mInstanceState = null;
}
}
用偽代碼表示這層關係:
ListView {
Observer observer {
onChange() { change; }
}
setAdapter(Adapter adapter) {
adapter.register(observer);
}
}
Adapter {
List<observer> mObservable;
register(observer) { mObservable.add(observer); }
notifyDataSetChanged() {
for (i = mObserverable.size() - 1; i >= 0; i--) {
mObserverable.get(i).onChange();
}
}
}
結論很清晰:Adapter 持有一組 Observer,控制項在 setAdapter 時把自己註冊進去,Adapter 通知時控制項就重新 addView 並 requestLayout。
public interface GrideTagBaseAdapter {
List<view> getViews();
}
public abstract class AbsGridTagsAdapter implements GrideTagBaseAdapter {
DataSetObservable mObservable = new DataSetObservable();
/** 通知所有監聽者資料已改變 */
public void notification() {
mObservable.notifyChanged();
}
public void registerObserve(DataSetObserver observer) {
mObservable.registerObserver(observer);
}
public void unregisterObserve(DataSetObserver observer) {
mObservable.unregisterObserver(observer);
}
}
直接借用 android.database.DataSetObservable 可以省下自己實作觀察者列表的功夫,這也是 ListView 原本的選擇。
實作 getViews(),把資料轉成 View 清單。這裡為每個標籤指定 GridTagView.LayoutParams 並設定 margin,示範自訂 margin 的用法:
public class MyGridTagAdapter extends AbsGridTagsAdapter {
private Context mContext;
private List<string> mTags;
public MyGridTagAdapter(Context context, List<string> tags) {
mContext = context;
mTags = tags;
}
@Override
public List<view> getViews() {
List<view> list = new ArrayList<>();
for (int i = 0; i < mTags.size(); i++) {
TextView tv = (TextView) LayoutInflater.from(mContext)
.inflate(R.layout.grid_tag_item_text, null);
tv.setText(mTags.get(i));
GridTagView.LayoutParams lp = new GridTagView.LayoutParams(
GridTagView.LayoutParams.WRAP_CONTENT,
GridTagView.LayoutParams.WRAP_CONTENT);
lp.margin(UIUtil.dp2px(mContext, 5)); // 四邊各留 5dp
tv.setLayoutParams(lp);
list.add(tv);
}
return list;
}
}
public class GridTagView extends ViewGroup {
private int mLines = 1;
private int mWidthSize = 0;
private AbsGridTagsAdapter mAdapter;
private GTObserver mObserver = new GTObserver();
public GridTagView(Context context) { this(context, null); }
public GridTagView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
public GridTagView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setAdapter(AbsGridTagsAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterObserve(mObserver); // 換 adapter 先解除舊的
}
mAdapter = adapter;
mAdapter.registerObserve(mObserver);
mAdapter.notification(); // 主動觸發一次刷新
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int curWidthSize = 0;
int childHeight = 0;
mLines = 1;
for (int i = 0; i < getChildCount(); ++i) {
View child = getChildAt(i);
measureChild(child, widthMeasureSpec, heightMeasureSpec);
curWidthSize += getChildRealWidthSize(child);
if (curWidthSize > widthSize) {
// 放不下就換行:寬度重算,行數 +1
curWidthSize = getChildRealWidthSize(child);
mLines++;
}
if (childHeight == 0) {
// 第一次計算時以子視圖高度作為行高基準
childHeight = getChildRealHeightSize(child);
}
}
mWidthSize = widthSize;
setMeasuredDimension(widthSize, childHeight == 0 ? heightSize : childHeight * mLines);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (getChildCount() == 0) return;
int childCount = getChildCount();
LayoutParams lp = getChildLayoutParams(getChildAt(0));
// 起始左邊界 = 自身 paddingLeft + 子元件 leftMargin
int left = getPaddingLeft() + lp.leftMargin;
int top = getPaddingTop() + lp.topMargin;
int curLeft = left;
for (int i = 0; i < childCount; ++i) {
View child = getChildAt(i);
int right = curLeft + getChildRealWidthSize(child);
if (right > mWidthSize) {
// 超出右界:換到下一行,左邊界還原、上邊界往下推
top += getChildRealHeightSize(child);
curLeft = left;
}
child.layout(curLeft, top,
curLeft + child.getMeasuredWidth(), top + child.getMeasuredHeight());
curLeft += getChildRealWidthSize(child); // 下一個的起點是這個的終點
}
}
/** 子視圖實際佔用寬度,必須含 margin 否則 margin 不生效 */
private int getChildRealWidthSize(View child) {
LayoutParams lp = getChildLayoutParams(child);
return child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
}
/** 子視圖實際佔用高度,同樣含上下 margin */
private int getChildRealHeightSize(View child) {
LayoutParams lp = getChildLayoutParams(child);
return child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin;
}
private LayoutParams getChildLayoutParams(View child) {
LayoutParams lp;
if (child.getLayoutParams() instanceof LayoutParams) {
lp = (LayoutParams) child.getLayoutParams();
} else {
lp = (LayoutParams) generateLayoutParams(child.getLayoutParams());
}
return lp;
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attr) {
return new LayoutParams(getContext(), attr);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return new LayoutParams(p);
}
/** 自訂 LayoutParams,讓 XML 與程式碼都能設定 margin */
public static class LayoutParams extends MarginLayoutParams {
public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); }
public LayoutParams(int width, int height) { super(width, height); }
public LayoutParams(MarginLayoutParams source) { super(source); }
public LayoutParams(ViewGroup.LayoutParams source) { super(source); }
public void marginLeft(int left) { this.leftMargin = left; }
public void marginRight(int r) { this.rightMargin = r; }
public void marginTop(int t) { this.topMargin = t; }
public void marginBottom(int b) { this.bottomMargin = b; }
public void margin(int m) {
this.leftMargin = m; this.rightMargin = m;
this.topMargin = m; this.bottomMargin = m;
}
}
private class GTObserver extends DataSetObserver {
@Override
public void onChanged() {
removeAllViews();
List<view> list = mAdapter.getViews();
for (int i = 0; i < list.size(); i++) {
addView(list.get(i));
}
requestLayout(); // 別忘了請求重新佈局
}
@Override
public void onInvalidated() {
Log.d("Mrz", "fd");
}
}
}
public class MainActivity extends AppCompatActivity {
MyGridTagAdapter adapter;
GridTagView mGridTag;
List<string> mList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridTag = findViewById(R.id.grid_tags);
mList = ListUtil.getGridTagsList(20);
adapter = new MyGridTagAdapter(this, mList);
mGridTag.setAdapter(adapter);
}
/** 換一批標籤 */
public void onClick(View v) {
mList.clear();
mList.addAll(ListUtil.getGridTagsList(20));
adapter.notification();
}
}
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent"
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
tools:context="humoursz.gridtag.test.MainActivity">
<humoursz.gridtag.test.widget.gridtagview
android:id="@+id/grid_tags"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</humoursz.gridtag.test.widget.gridtagview>
<button android:layout_centerinparent="true"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:onclick="onClick" android:text="換一批" />
</relativelayout>
這個實作把「自訂 ViewGroup 的最小骨架」示範得很清楚,但要變成可重用元件,還有幾處值得處理:
行高不齊。目前所有行都用第一個子元件的高度當基準(childHeight == 0 那個判斷),若標籤文字長度差異大導致換行,高度會被低估。正確做法是記錄每一行的最大高度,onMeasure 累加、onLayout 依行推進。
onMeasure 沒處理 MeasureSpec 模式。現在無條件用 widthSize 當寬度,在 wrap_content 情境下會得到錯誤結果。應該判斷 MeasureSpec.getMode(),AT_MOST 與 EXACTLY 各自處理。
垂直方向的onLayout 裡 top 每次都直接加子元件高度,沒把 bottomMargin 獨立算進換行位移,標籤間距會比預期緊。把 getChildRealHeightSize() 用在換行位移上是對的,但要確認它已含上下 margin——這裡是的,所以主要是 onMeasure 的行高基準要一起改。
沒有間距與點擊事件。實務上的標籤雲幾乎都需要「點擊某個標籤」與「超出 N 行時折疊/展開」。前者在 GTObserver 產生 View 時掛上 OnClickListener 並回呼給外部監聽器即可;後者需要把 mLines 存成成員並提供 setter。
最后一句提醒:若你的專案已使用 ConstraintLayout 或 Jetpack Compose,標籤雲有現成方案(如 FlowLayout、Compose 的 FlowRow)可直接用,不必自己造輪子。但自己寫過一次,你會對「測量與佈局是兩件不同的事」這句話有真正的體會——而這是自訂控制項唯一的分水嶺。
自製 ImageLoader:從 LruCache 到非同步圖片載入的完整實作
先看幾張效果圖: 在載入大量圖片時,我們採用後進先出策略(滑到哪裡就先載入哪裡的圖片),既節省記憶體,使用者體驗也更好。下面就來打造自己的 ImageLoader。
Android Activity 四種 launchMode 啟動模式完整解析
Activity 的啟動模式決定了實例創建、任務棧管理與頁面復用方式。Android 中常見的 launchMode 有四種:standard、singleTop、sin
Android 分類選單實作:Fragment 與 RadioGroup 的組合應用
在許多應用中,使用者點擊頂部按鈕後會彈出分類選單。這類互動可以透過 Fragment 與 RadioGroup 組合完成,既能保持畫面整潔,也方便日後維護。 整體結構 主
OpenGL ES 2.0 for Android 實戰:從三角形到彩色立方體
前面幾篇都在處理 OpenGL ES 2.0 的二維繪製,現在該邁進三維世界了。三維远比二維有趣,但複雜度也高出不少——在 Unity3D 裡拖一下就有一個立方體,而在