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

自定義下拉刷新 / 上拉加載控件的優化歷程

編輯:關於 Android 程式設計

之前那篇博文的出現,起因於前段時間自己寫一個練手 App 時遇到了下拉刷新、上拉加載的需求。如今這類功能越來越普遍,幾乎絕大多數應用都會用到。市面上已有不少現成「輪子」可用,但既然是練手之作,何不自己造一造「輪子」呢?

以前這類需求基本都用在 ListView 上,前兩年 PullToRefreshListView 還很流行。但隨著 RecyclerView 等出現,這種針對 ListView 的擴展就顯得不夠用了。於是我決定:自定義一個能通用該功能的 ViewGroup,而不是針對某種特定 View 做擴展。完成後記錄了思路與收獲,也收到了不少建議。由於水平、時間與精力所限,回頭看時發現很多可以改進的地方,於是便有了這次優化,本文總結優化思路與收獲。


一、上拉、下拉動畫效果的修改

最初的實現為了有趣,採用了比較花哨的 Loading 效果:

但有朋友指出,若想真正使用這個控件,這種動畫不太實用。想想也是,發布到應用市場時確實不夠嚴肅。於是改用簡練、提示清晰的動畫風格。改動並不難,主要思路仍是根據滑動距離讓 ViewGroup 進入不同狀態,再根據狀態顯示不同提示;旋轉箭頭只需一張向下箭頭素材加屬性動畫即可。


二、onMeasure 和 onLayout 的思路優化

最初我把 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);
    }
}

如此便能解決上面提到的問題:


五、加入 NestedScroll 嵌套滑動機制

完成上述改造後仍有改進余地。以 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

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