編輯:關於 Android 程式設計
上一篇講了列表樣式的基礎用法,包括通過 LayoutManager 控制方向、addItemDecoration() 添加間隔、setItemAnimator() 設置增刪動畫等。這一篇聚焦兩個更複雜的場景:網格與瀑布流。
之所以把「自定義間隔」留到這裡講,是因為列表樣式的間隔線實在太簡單——一條線畫到底就完事了。而在網格布局中,你需要判斷哪個位置該畫、哪個位置不該畫,複雜度立刻上升了一個檔次。
網格樣式由 GridLayoutManager 控制,兩個常用構造函數:
GridLayoutManager(Context context, int spanCount)——默認豎直方向的網格。
GridLayoutManager(Context context, int spanCount, int orientation, boolean reverseLayout)——可指定方向(OrientationHelper.HORIZONTAL 或 VERTICAL)以及是否逆向排列。
兩個構造中的 spanCount 都表示每行或每列的 item 數量,設為 1 時就退化成列表樣式。
// 豎直方向,每行 4 個 mLayoutManager = new GridLayoutManager(this, 4, OrientationHelper.VERTICAL, false); mRecyclerView.setLayoutManager(mLayoutManager);

圖-1 網格無間隔
效果出來了,但醜得難以直視——完全沒有間隔。系統自帶的 DividerItemDecoration 在網格下並不好用,還是得自己寫。
新建 md_divider.xml,一個灰色矩形:
<!--?xml version="1.0" encoding="utf-8"?-->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/darker_gray" />
<size android:width="4dp" android:height="4dp" />
</shape>
在自定義主題裡替換 listDivider:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:listDivider">@drawable/md_divider</item>
</style>
核心邏輯是:遍歷所有可見 child,判斷每個位置是否需要畫右間隔和下方間隔。判斷規則不難——豎直方向時,每列最後一個不畫豎直間隔,最後一行不畫水平間隔;水平方向同理旋轉九十度。
public class MDGridRvDividerDecoration extends RecyclerView.ItemDecoration {
private static final int[] ATTRS = new int[]{ android.R.attr.listDivider };
/** 用于繪制間隔的樣式 */
private Drawable mDivider;
public MDGridRvDividerDecoration(Context context) {
final TypedArray a = context.obtainStyledAttributes(ATTRS);
mDivider = a.getDrawable(0);
a.recycle();
}
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
int childCount = parent.getChildCount();
GridLayoutManager lm = (GridLayoutManager) parent.getLayoutManager();
int spanCount = lm.getSpanCount();
int orientation = lm.getOrientation();
boolean isDrawHorizontalDivider;
boolean isDrawVerticalDivider;
// 最後一行(列)的 item 個數
int extra = childCount % spanCount;
extra = extra == 0 ? spanCount : extra;
for (int i = 0; i < childCount; i++) {
isDrawVerticalDivider = true;
isDrawHorizontalDivider = true;
// 豎直方向:最右一列不畫豎直間隔
if (orientation == OrientationHelper.VERTICAL && (i + 1) % spanCount == 0) {
isDrawVerticalDivider = false;
}
// 豎直方向:最後一行不畫水平間隔
if (orientation == OrientationHelper.VERTICAL && i >= childCount - extra) {
isDrawHorizontalDivider = false;
}
// 水平方向:最下一行不畫水平間隔
if (orientation == OrientationHelper.HORIZONTAL && (i + 1) % spanCount == 0) {
isDrawHorizontalDivider = false;
}
// 水平方向:最後一列不畫豎直間隔
if (orientation == OrientationHelper.HORIZONTAL && i >= childCount - extra) {
isDrawVerticalDivider = false;
}
if (isDrawHorizontalDivider) {
drawHorizontalDivider(c, parent, i);
}
if (isDrawVerticalDivider) {
drawVerticalDivider(c, parent, i);
}
}
}
/**
* 為每個 item 留出間隔的位置。
* 注意:最後一行(列)不需要在相應方向留出空間,否則會多出一段空白。
*/
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
RecyclerView.State state) {
int spanCount = ((GridLayoutManager) parent.getLayoutManager()).getSpanCount();
int orientation = ((GridLayoutManager) parent.getLayoutManager()).getOrientation();
int position = parent.getChildLayoutPosition(view);
if (orientation == OrientationHelper.VERTICAL && (position + 1) % spanCount == 0) {
outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
return;
}
if (orientation == OrientationHelper.HORIZONTAL && (position + 1) % spanCount == 0) {
outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);
return;
}
outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight());
}
/** 繪制豎直間隔線 */
private void drawVerticalDivider(Canvas canvas, RecyclerView parent, int position) {
final View child = parent.getChildAt(position);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getTop() - params.topMargin;
final int bottom = child.getBottom() + params.bottomMargin + mDivider.getIntrinsicHeight();
final int left = child.getRight() + params.rightMargin;
final int right = left + mDivider.getIntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
/** 繪制水平間隔線 */
private void drawHorizontalDivider(Canvas canvas, RecyclerView parent, int position) {
final View child = parent.getChildAt(position);
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + params.bottomMargin;
final int bottom = top + mDivider.getIntrinsicHeight();
final int left = child.getLeft() - params.leftMargin;
final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth();
mDivider.setBounds(left, top, right, bottom);
mDivider.draw(canvas);
}
}
應用的方式一行搞定:
mRecyclerView.addItemDecoration(new MDGridRvDividerDecoration(this));

圖-2 網格有間隔
網格樣式的自定義間隔,歸納起來就是四步:
1、準備間隔樣式,XML drawable 或圖片都行;
2、覆蓋應用主題的 listDivider 屬性;
3、繼承 RecyclerView.ItemDecoration,實現 onDraw 與 getItemOffsets;
4、通過 addItemDecoration 掛上去。
第三步是唯一的難點,上面的代碼提供了一種思路,可以按需借鑒。
瀑布流的布局管理器是 StaggeredGridLayoutManager,構造函數只有一個:StaggeredGridLayoutManager(int spanCount, int orientation)。
mLayoutManager = new StaggeredGridLayoutManager(2, OrientationHelper.VERTICAL); mRecyclerView.setLayoutManager(mLayoutManager); mRecyclerView.setAdapter(mAdapter); mRecyclerView.addItemDecoration(new MDStaggeredRvDividerDecotation(this));
要形成瀑布流視覺,每個 item 的高度必須有差異,否則就退化成普通網格了。示例中準備了兩種高度:80dp 與 100dp。
view_rv_staggered_item.xml:
<!--?xml version="1.0" encoding="utf-8"?-->
<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="80dp"
android:orientation="vertical">
<TextView
android:id="@+id/item_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:text="item" />
</LinearLayout>
view_rv_staggered_item_two.xml 結構相同,只把 layout_height 改成 100dp。
兩種布局由 Adapter 內部通過 getItemViewType 決定:
public class MDStaggeredRvAdapter extends RecyclerView.Adapter<MDStaggeredRvAdapter.ViewHolder> {
private ArrayList<String> mData;
public MDStaggeredRvAdapter(ArrayList<String> data) {
this.mData = data;
}
public void updateData(ArrayList<String> data) {
this.mData = data;
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
// 兩列交替使用兩種高度,形成錯落效果
return position % 2;
}
@Override
public MDStaggeredRvAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
if (viewType == 1) {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_rv_staggered_item, parent, false);
} else {
v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.view_rv_staggered_item_two, parent, false);
}
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(MDStaggeredRvAdapter.ViewHolder holder, int position) {
holder.mTv.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView mTv;
public ViewHolder(View itemView) {
super(itemView);
mTv = (TextView) itemView.findViewById(R.id.item_tv);
}
}
}
示例裡的 MDStaggeredRvDividerDecotation 一開始是直接拷貝網格那套邏輯的,結果:

圖-3 瀑布流 2 列
間隔線完全不是我們想要的樣子。對比一下兩種布局的 item 排布規律:

圖-4 兩者對比
網格樣式的規律很清晰:從左到右、從上到下嚴格按順序填滿每一行。
瀑布流則是從上到下、從左到右排列,但多了一個「高度優先」規則:哪一列的當前底部位置最低,下一個 item 就放進去。圖-3 中的第三個 item 之所以出現在左列,就是因為那個位置當時最矮。
這就意味着,在 onDraw 裡根本無法預知某個 item 究竟落在哪一列、以及它周圍是否需要間隔——你算不出來,因為它取決於前面所有 item 的高度累加結果。而且向下滑動加載新數據後,整個排布還會變化。
瀑布流加間隔,靠 ItemDecoration 幾乎走不通,可行的方案有兩個:
在 item 布局裡直接設置 padding 或 margin;
在代碼中動態修改 itemView 的 padding/margin。
接著要決定間隔加在哪幾條邊,兩種做法各有問題:
四周都設——相鄰 item 之間的間距會變成設定值的兩倍;
相鄰兩邊設(比如右下)——最右一列右側、最後一行下方會貼著父容器邊緣沒有間隔,與其他位置視覺上不統一。
第二種問題的解法是:給父容器 RecyclerView 也加上對應方向的 padding,讓整體間隔看起來一致。示例選擇在 item 布局裡設間隔,好處是顏色可以在 XML 中直接控制,用一個「間隔色背景 + 內縮子 view」的套路就能畫出間隔線。
修改後的 view_rv_staggered_item.xml:
<!--?xml version="1.0" encoding="utf-8"?-->
<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="@dimen/md_common_view_height"
android:background="@color/md_divider"
android:orientation="vertical"
android:paddingBottom="5dp"
android:paddingRight="5dp">
<TextView
android:id="@+id/item_tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/md_white"
android:gravity="center"
tools:text="item" />
</LinearLayout>
view_rv_staggered_item_two.xml 同樣處理,只把高度換成 100dp。
最後給 RecyclerView 加上與間隔同值的 padding,把邊緣的缺口補齊。

圖-5 瀑布流最終效果
間隔問題基本完美解決。有個小細節:滑動時頂部會一直露出一條灰色間隔,去掉 RecyclerView 布局文件中的 paddingTop 即可。
列表、網格、瀑布流三者在某種意義上是同一套東西的不同參數組合:
GridLayoutManager 的 spanCount 設為 1,就是列表;
StaggeredGridLayoutManager 如果 item 等高(豎直方向)或等寬(水平方向),就是網格;
StaggeredGridLayoutManager 的 spanCount 設為 1,就是列表。
選擇時可以這樣判斷:規則網格用 GridLayoutManager + 自定義 ItemDecoration;不規則瀑布流用 StaggeredGridLayoutManager + padding 方案。記住一個原則——ItemDecoration 適合位置可預測的布局,位置無法預測時就換成 padding。
RecyclerView 的能力遠不止這些,單個 item 橫滑、拖拽換位等官方也都有支持,後續再逐一展開。
Android 定位策略指南:兼顧精度與電量的取捨
本文所述的策略適用於平台內建的定位 API(android.location)。若使用 Google Play 服務中的融合定位 API(Fused Location P
Android 底部導航欄實作:用 TabHost 打造選項卡式主頁
在許多 Android 應用中,底部導航欄是很常見的互動模式。它能讓使用者快速切換主要頁面,也能讓整體操作更直覺。本文以 TabHost 為核心,示範如何打造一個包含多個
Android 底部支付密碼彈窗的實作與踩坑記錄
這篇做一個從畫面底部彈起的支付輸入框,重點在 PopupWindow 的封裝方式,以及幾個處理不好就很醜的細節。 效果: 思路: 1. 繼承 PopupWindow 自
Android 繪製 QQ 風格登入界面的完整程式碼
先看一下成果: 這個看起來簡單的畫面,實際做下去會碰到四個不大不小的問題: 1、如何為 EditText 設定自定義背景。 2、頁面一打開 EditText 就自