編輯:關於 Android 程式設計
上一篇我們走過自定義 ViewGroup 的基本步驟,並完成了一個 CustomGridLayout 範例。本篇要挑戰的是瀑布流。
當畫面上有大量照片需要呈現時,GridView 是最直覺的照片牆,但它實在太整齊了。有時候不規則反而是種美——瀑布流正是這樣一種錯落有致的展示方式。以下嘗試用自定義 ViewGroup 來實作。
實作瀑布流的思路有幾種,我們逐一來看。
這種做法只需在上一篇的基礎上稍作調整,主要改動三處。
瀑布流中每張圖寬度相同、高度不一,無法用「top + 固定高度」推算出 bottom,因此索性把四個邊界都定義出來:
public static class LayoutParams extends ViewGroup.LayoutParams {
public int left = 0;
public int top = 0;
public int right = 0;
public int bottom = 0;
public LayoutParams(Context arg0, AttributeSet arg1) { super(arg0, arg1); }
public LayoutParams(int arg0, int arg1) { super(arg0, arg1); }
public LayoutParams(android.view.ViewGroup.LayoutParams arg0) { super(arg0); }
}
每張圖寬度一致、高度等比縮放,因此 layout_height 實際上派不上用場。我們用一個 top[colums] 陣列記錄每一列目前的累積高度,每次要放新圖時,就挑「目前最矮的那一列」放進去,這樣各列高度才會趨於平衡。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
measureChildren(widthMeasureSpec, heightMeasureSpec);
int childCount = this.getChildCount();
// wrap_content 時,childWidth 取子 View 寬度的最大值;否則依欄數平均分配
if (widthMode == MeasureSpec.AT_MOST) {
for (int i = 0; i < childCount; i++) {
childWidth = Math.max(childWidth, getChildAt(i).getMeasuredWidth());
}
} else if (widthMode == MeasureSpec.EXACTLY) {
childWidth = (sizeWidth - (colums - 1) * hSpace) / colums;
}
// onMeasure 會被呼叫兩次,必須先清空中高度記錄
clearTop();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
childHeight = child.getMeasuredHeight() * childWidth / child.getMeasuredWidth();
LayoutParams lParams = (LayoutParams) child.getLayoutParams();
int minColum = getMinHeightColum(); // 找最矮的一列
lParams.left = minColum * (childWidth + hSpace);
lParams.top = top[minColum];
lParams.right = lParams.left + childWidth;
lParams.bottom = lParams.top + childHeight;
top[minColum] += vSpace + childHeight; // 更新該列高度
}
int wrapWidth;
if (childCount < colums) {
wrapWidth = childCount * childWidth + (childCount - 1) * hSpace;
} else {
wrapWidth = colums * childWidth + (colums - 1) * hSpace;
}
int wrapHeight = getMaxHeight();
setMeasuredDimension(widthMode == MeasureSpec.AT_MOST ? wrapWidth : sizeWidth, wrapHeight);
}
由於 LayoutParams 已存好四個座標,直接套用即可:
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int childCount = this.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
LayoutParams lParams = (LayoutParams) child.getLayoutParams();
child.layout(lParams.left, lParams.top, lParams.right, lParams.bottom);
}
}
這裡有個容易踩到的坑:每次設定子 View 的 LayoutParams 前,必須先把 top[] 陣列歸零。因為 onMeasure 與 onLayout 都會被呼叫兩次,若不清零,第二次的座標就會在第一次的基礎上繼續累加,導致版面全亂。
new 出 ViewGroup 的瞬間,getWidth() 與 getHeight() 都是 0。呼叫 onMeasure() 完成測量後,View 的寬高才確定下來;而寬高一旦改變,就會再次觸發 onMeasure 與 onLayout。這就是它會跑兩次的原因,也是自定義 ViewGroup 必須具備「可重入」特性的根本理由。
public interface OnItemClickListener {
void onItemClick(View v, int index);
}
public void setOnItemClickListener(final OnItemClickListener listener) {
for (int i = 0; i < getChildCount(); i++) {
final int index = i;
getChildAt(i).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
listener.onItemClick(v, index);
}
});
}
}
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res/com.hx.waterfalllayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#303030">
<com.hx.waterfalllayout.WaterfallLayout
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#1e1d1d"
app:hSpace="10"
app:numColumns="3"
app:vSpace="10">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/crazy_1" />
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:src="@drawable/crazy_2" />
<!-- 其餘 ImageView 依此類推 -->
</com.hx.waterfalllayout.WaterfallLayout>
</ScrollView>
最外層包 ScrollView,是因為照片牆可以無限擴充,超出螢幕後需要能捲動。當然,這些 ImageView 也可以改用 Java 動態 addView,程式碼會更乾淨。
點擊回呼的使用方式:
((WaterfallLayout) findViewById(R.id.waterfallLayout))
.setOnItemClickListener(new WaterfallLayout.OnItemClickListener() {
@Override
public void onItemClick(View v, int index) {
Toast.makeText(MainActivity.this, "item=" + index, Toast.LENGTH_SHORT).show();
}
});

這是很常見的困擾,原因藏在 ScrollView 的源碼裡:它會以 UNSPECIFIED 模式去測量子 View 的高度,而 GridView、ListView、ViewPager 這類本身會捲動的元件遇到 UNSPECIFIED 時,只會量出一個螢幕高的結果。這也解釋了為什麼它們嵌在 ScrollView 裡總是顯示不完整。
解法是包一層,在 onMeasure 中把高度規格改成足夠大的 AT_MOST:
public class OtherGridView extends GridView {
public OtherGridView(Context paramContext, AttributeSet paramAttributeSet) {
super(paramContext, paramAttributeSet);
}
/** 在 ScrollView 內,需要自行撐開高度 */
@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}

若直接繼承 ScrollView,就不必在外面再包一層捲動容器。這種做法不需要覆寫 onMeasure,只要處理 onLayout。
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
// 只在首次版面完成時初始化,取得各列寬度後開始載入圖片
if (changed && !loadOnce) {
firstColumn = (LinearLayout) findViewById(R.id.first_column);
secondColumn = (LinearLayout) findViewById(R.id.second_column);
thirdColumn = (LinearLayout) findViewById(R.id.third_column);
columnWidth = firstColumn.getWidth();
loadOnce = true;
loadImages();
}
}
public void loadImages() {
for (int i = 0; i < imageRes.length; i++) {
Bitmap bitmap = resource2Bitmap(imageRes[i]);
if (bitmap != null) {
// 依實際寬高比縮放,保持不變形
double ratio = bitmap.getWidth() / (columnWidth * 1.0);
int scaledHeight = (int) (bitmap.getHeight() / ratio);
addImage(i, bitmap, columnWidth, scaledHeight);
}
}
}
private void addImage(int index, Bitmap bitmap, int imageWidth, int imageHeight) {
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(imageWidth, imageHeight);
ImageView imageView = new ImageView(getContext());
imageView.setLayoutParams(params);
imageView.setImageBitmap(bitmap);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setPadding(5, 5, 5, 5);
findColumnToAdd(imageView, imageHeight).addView(imageView);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClick(v, index);
}
}
});
}
/** 挑出目前最矮的一列放圖,讓各列高度保持接近 */
private LinearLayout findColumnToAdd(ImageView imageView, int imageHeight) {
if (firstColumnHeight <= secondColumnHeight) {
if (firstColumnHeight <= thirdColumnHeight) {
firstColumnHeight += imageHeight;
return firstColumn;
}
thirdColumnHeight += imageHeight;
return thirdColumn;
} else {
if (secondColumnHeight <= thirdColumnHeight) {
secondColumnHeight += imageHeight;
return secondColumn;
}
thirdColumnHeight += imageHeight;
return thirdColumn;
}
}
寫到這裡照片牆已經能跑起來了,相當省事。但這種做法也有明顯侷限:欄數被寫死成三欄,擴充性不佳。
值得留意的是,這份程式碼裡並沒有自己實作子 View 的 layout(),那子 View 是怎麼定位的?答案是交給了 LinearLayout——每個子 View 被 addView 進某一列的 LinearLayout 之後,由 LinearLayout 負責呼叫它們的 layout()。這其實就跟自定義 View 中的「組合控制項」思路如出一轍。
public OnItemClickListener onItemClickListener;
public interface OnItemClickListener {
void onItemClick(View v, int index);
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
由於程式碼中固定三欄,XML 需要三個水平排列的 LinearLayout:
<com.hx.waterfalllayout.ScrollWaterfallLayout
android:id="@+id/scrollWaterfallLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/first_column"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/second_column"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" />
<LinearLayout
android:id="@+id/third_column"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" />
</LinearLayout>
</com.hx.waterfalllayout.ScrollWaterfallLayout>
點擊回呼:
((ScrollWaterfallLayout) findViewById(R.id.scrollWaterfallLayout))
.setOnItemClickListener(new ScrollWaterfallLayout.OnItemClickListener() {
@Override
public void onItemClick(View v, int index) {
Toast.makeText(MainActivity.this, "item=" + index, Toast.LENGTH_SHORT).show();
}
});

原始碼下載:https://xiazai.jb51.net/201609/yuanma/Android-WaterfallLayout(jb51.net).rar
兩種做法各有取捨:繼承 ViewGroup 擴充性最好,欄數、間距都能自由設定,但必須自己處理測量與定位;繼承 ScrollView 實作最快,卻犧牲了彈性。若是正式專案,我會建議走第一條路,並把欄數、間距、載入更多(分頁)都做成可設定項目。
Android launchMode 詳解:singleTask 與 singleInstance 實測對比
網路上介紹 Android launchMode 的文章不少,但關於 singleTask 與 singleInstance 這兩種模式,評論區一直有些爭議。本文用實例把
Android ViewFlipper 基本用法詳解
ViewFlipper 和 ViewPager 頗為相似,兩者都是一種 View 容器,內部都能添加多個 View。區別在於 ViewPager 可以透過左右滑動來切換
自定義View打造Android柱狀圖:橫向、縱向與比例圖三合一
做專案的時候需要一種簡單的橫向柱狀圖,翻了不少現成框架卻總覺得不合手,最後索性自己寫了一個自定義 View,順手把三種常見的柱狀圖形態都封裝進去了。 先看成果 第一種是
MPAndroidChart 折線圖實戰:資料綁定、樣式設定與常見坑位
從資料到折線圖 本文以 MPAndroidChart 的 LineChart 為例,整理折線圖在實際專案中的資料綁定、樣式設定與常見問題。 LineChartTools