編輯:關於 Android 程式設計
之前那篇博文的出現,起因於前段時間自己寫一個練手 App 時遇到了下拉刷新、上拉加載的需求。如今這類功能越來越普遍,幾乎絕大多數應用都會用到。市面上已有不少現成「輪子」可用,但既然是練手之作,何不自己造一造「輪子」呢?
以前這類需求基本都用在 ListView 上,前兩年 PullToRefreshListView 還很流行。但隨著 RecyclerView 等出現,這種針對 ListView 的擴展就顯得不夠用了。於是我決定:自定義一個能通用該功能的 ViewGroup,而不是針對某種特定 View 做擴展。完成後記錄了思路與收獲,也收到了不少建議。由於水平、時間與精力所限,回頭看時發現很多可以改進的地方,於是便有了這次優化,本文總結優化思路與收獲。
最初的實現為了有趣,採用了比較花哨的 Loading 效果:

但有朋友指出,若想真正使用這個控件,這種動畫不太實用。想想也是,發布到應用市場時確實不夠嚴肅。於是改用簡練、提示清晰的動畫風格。改動並不難,主要思路仍是根據滑動距離讓 ViewGroup 進入不同狀態,再根據狀態顯示不同提示;旋轉箭頭只需一張向下箭頭素材加屬性動畫即可。
最初我把 ViewGroup 裡的 child view 按定義先後順序由上至下排列,導致滑動邏輯混亂。比如處理下拉沖突起時,只能通過 getChildAt(firstChildIndex) 判斷最上方子 View;處理上拉時又要判斷 getChildAt(lastChildIndex),寫法十分彆扭。
於是我研讀了 SwipeRefreshLayout 源碼並加以借鑒。先看這樣一個布局,猜猜它的最終效果:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="button" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher" />
<View
android:layout_width="match_parent"
android:layout_height="1200dp"
android:background="#000000" />
</LinearLayout>
最終效果如下:

可以發現:雖然把 SwipeRefreshLayout 內的 LinearLayout 高度設為 300dp,最終卻像 match_parent;雖然把後面 View 高度設為 1200dp,卻根本顯示不出來。答案要到 onMeasure 與 onLayout 中尋找。先看部分 onMeasure 代碼:
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
mTarget.measure(
MeasureSpec.makeMeasureSpec(
getMeasuredWidth() - getPaddingLeft() - getPaddingRight(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(
getMeasuredHeight() - getPaddingTop() - getPaddingBottom(), MeasureSpec.EXACTLY));
// 省略若干...
}
可見它先判斷 mTarget 是否為空,為空則調用 ensureTarget():
private void ensureTarget() {
if (mTarget == null) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (!child.equals(mCircleView)) {
mTarget = child;
break;
}
}
}
}
這個方法遍歷 child view,把第一個不為 mCircleView(默認添加的下拉小圈圈)的子 View 作為 mTarget。回到 onMeasure,對 mTarget 測量的結果始終是 EXACTLY 模式的 SwipeRefreshLayout 寬高減去內邊距,這就解釋了為什麼 300dp 最終佔滿了窗口。再看 onLayout:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
final int width = getMeasuredWidth();
final int height = getMeasuredHeight();
if (getChildCount() == 0) {
return;
}
if (mTarget == null) {
ensureTarget();
}
if (mTarget == null) {
return;
}
final View child = mTarget;
final int childLeft = getPaddingLeft();
final int childTop = getPaddingTop();
final int childWidth = width - getPaddingLeft() - getPaddingRight();
final int childHeight = height - getPaddingTop() - getPaddingBottom();
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
// mCircleView 的 layout 省略...
}
可見 measure 與 layout 都只針對 mTarget(第一個 child),這就解釋了後面那個 1200dp 的 View 為何不顯示。
為什麼這種方式更優秀?因為我們真正的需求是「支持下拉、上拉」的 ViewGroup,根本不用過多考慮 child 的測量與置位——這些交給 LinearLayout、RelativeLayout 等即可。這樣處理滑動沖突時只需針對 mTarget,邏輯變得明確。我的布局裡其實不止一個 View(3 個 Button + 1 個 ImageView),但對它們的測量與置位不應由自定義 ViewGroup 負責。
<me.hwang.widgets.smartpullablelayout
xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:library="https://schemas.android.com/apk/res-auto"
android:id="@+id/layout_pullable"
android:layout_width="match_parent"
android:layout_height="match_parent"
library:smart_ui_enable_pull_up="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按鈕一" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按鈕二" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="按鈕三" />
<ImageView
android:id="@+id/iv_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher" />
</LinearLayout>
</me.hwang.widgets.smartpullablelayout>
運行效果:

當然這種方式並非萬無一失。若寫出下面這種意圖不明的布局(既想對整個 LinearLayout 刷新,又想對局部 ListView 刷新),控件作者無法猜測你的目的,就會出現滑動 bug:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<ListView
android:id="@+id/lv_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
若你的需求是對局部 ListView 刷新,則應把 ListView 的父容器高度設為 match_parent:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<ListView
android:id="@+id/lv_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</Button>
<Button
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
這一點是朋友提出來的,確有必要。最初沒有阻力時,快速下滑會讓整個視圖飛快下滑,體驗不佳,還得判斷滑動距離上限;加入阻力後:

對比可見體驗舒服不少,而且不再需要「達到一定距離後禁止滑動」的判斷。實現很簡單:設置一個阻力因子(如 0.5),讓每次實際滑動距離乘以阻力因子;滑動距離達到可釋放刷新的距離後再乘一次,就會給人「越往下越拉不動」的感覺。

之前與 ListView 配合時,我在 onInterceptTouchEvent 中處理沖突:若是下拉操作,先判斷 ListView 是否已滑到頂部,是則攔截事件自行處理,否則不攔截。邏輯本身沒問題,但由於對 AbsListView 了解不夠,發現一個惱人的問題:

先讓 ListView 下滑一點,再上滑到頂後繼續下拉,卻不起作用。原因在於 AbsListView 內部處理觸摸事件時有類似如下代碼:
final ViewParent parent = getParent();
if (parent != null) {
parent.requestDisallowInterceptTouchEvent(true);
}
也就是說,當 AbsListView 決定自己處理滑動時,會調用父視圖的 requestDisallowInterceptTouchEvent 禁止父視圖攔截事件,導致後續觸摸事件根本不經過我們的 onInterceptTouchEvent,沖突判斷自然不執行。解決方法靈感同樣來自 SwipeRefreshLayout:
public void requestDisallowInterceptTouchEvent(boolean b) {
// 防止在 child view 同樣具有垂直滑動能力時「偷」走滑動事件
if ((android.os.Build.VERSION.SDK_INT < 21 && mTarget instanceof AbsListView)
|| (mTarget != null && !ViewCompat.isNestedScrollingEnabled(mTarget))) {
// Nope.
} else {
super.requestDisallowInterceptTouchEvent(b);
}
}
如此便能解決上面提到的問題:

完成上述改造後仍有改進余地。以 ListView 為例,雖然體驗好了不少,但本質上仍依賴事件攔截機制:一旦自定義的 Parent ViewGroup 決定攔截事件,本次後續的 TouchEvent 就不再傳遞給 childView。
而對 RecyclerView 這類更「年輕」的控件,這不再是無解——Android 在 Lollipop 之後引入了 Nested Scroll(嵌套滑動)機制,RecyclerView 本身就支持。於是我也為自定義 ViewGroup 加上了這個能力。

加入嵌套滑動後,自定義 ViewGroup 與 RecyclerView 之間配合默契,體驗最好。核心思路是:
首先,RecyclerView 作為 NestedScrollingChild,每次處理滑動前會先通知 NestedScrollingParent 是否需要嵌套滑動;此時 Parent 可在 onNestedPreScroll 中預先滑動;最後 Child 處理完滑動後,會回調 onNestedScroll,把未消耗的 y 軸距離作為 dyUnconsumed 傳入。
有了這些基礎,我們可以:
在 onNestedPreScroll 中,若自定義 ViewGroup 已發生過滑動,則先滑動直到它恢復初始位置;反之若未發生滑動,則不預消耗,直接讓 Child 處理。在 onNestedScroll 中,把 Child 未消耗完的距離(dyUnconsumed)消耗掉。
以上就是這次自定義上拉加載、下拉刷新控件優化的思路總結與收獲。再次感歎,閱讀源碼雖有些辛苦,收穫卻最大。上文種種改動的啟發多來自 SwipeRefreshLayout;閱讀 onMeasure 時的困惑,也逼著我重新走了一遍 View 的繪制流程,補上了不少以前忽略的知識。項目源碼已上傳 GitHub,感興趣的朋友可參照源碼,多多指教。
https://github.com/RawnHwang/SmartAndroidWidgets
Android DiffUtil 全解析:RecyclerView 增量刷新與局部更新
一、它解決了什麼問題 DiffUtil 是 support-v7:24.2.0 引入的工具類,作用是比較新老兩個數據集,算出從舊數據到新數據的最小改動集合。說到數據集,搭
手機QQ語音怎麼轉文字?不方便聽語音時的解法
收到一長串語音,偏偏人在會議室或捷運上不方便播放——這是很多人都遇過的窘境。手機QQ有語音轉文字的機制,可以把說話內容變成可閱讀的文字,只是這個功能有幾個前提條件。操作步
從編程角度理解 Gradle 腳本:Android Studio 構建與編程
Android 開發從 Eclipse 轉向 Android Studio 後,Gradle 腳本成為必備知識。若把 Gradle 視為編程框架,並理解腳本與對象之間的對
對 Binder 的淺顯分析及 AIDL 的使用
作為 Android 開發者,平時很少直接接觸 Binder,但它作為 IPC(進程間通訊)機制中最關鍵的一環,非常值得了解。其實我們早已與它打過交道:bindServi