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

檢測 ScrollView 是否滾到頂部或底部:分頁與下拉刷新的基礎

編輯:關於 Android 程式設計

做分頁載入時,判斷「有沒有滑到底」決定要不要抓下一頁;做下拉刷新時,判斷「有沒有回到頂端」決定要不要顯示刷新提示。這兩個判斷的公式其實不難,但很容易用錯 View 的方法。

版面範例

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:id="@+id/scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/darker_gray"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="2000dip"
                android:text="text" />
        </LinearLayout>
    </ScrollView>
</RelativeLayout>

檢測程式碼

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ScrollView view = (ScrollView) findViewById(R.id.scroll_view);

        view.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {

                    case MotionEvent.ACTION_MOVE:
                        if (v.getScrollY() <= 0) {
                            Log.d("scroll view", "top");
                        } else if (view.getChildAt(0).getMeasuredHeight()
                                <= v.getHeight() + v.getScrollY()) {
                            Log.d("scroll view", "bottom");
                            Log.d("scroll view",
                                    "view.getMeasuredHeight() = " + view.getMeasuredHeight()
                                    + ", v.getHeight() = " + v.getHeight()
                                    + ", v.getScrollY() = " + v.getScrollY()
                                    + ", child.getMeasuredHeight() = "
                                    + view.getChildAt(0).getMeasuredHeight());
                        }
                        break;

                    default:
                        break;
                }
                return false;   // 不回傳 true,不干擾 ScrollView 自身的捲動
            }
        });
    }
}

三個數值分別代表什麼

這段邏輯最容易搞錯的就是這三個方法:

  • v.getScrollY():內容「往上捲出去」的距離。為 0 表示還在最頂端。
  • v.getHeight():ScrollView 這個 View 本身在螢幕上看起來的高度,也就是可視區大小。
  • view.getChildAt(0).getMeasuredHeight():裡面那個 LinearLayout(也就是全部內容)的實際高度。

實際 log 出來的數值大概是這樣:

view.getMeasuredHeight()               = 1038
v.getHeight()                          = 1038
v.getScrollY()                         = 2962
view.getChildAt(0).getMeasuredHeight() = 4000

驗算一下:4000 - 1038 = 2962,正好等於捲到底時的 scrollY。所以判斷式 childHeight <= viewHeight + scrollY 成立時,就是已經到底。

為什麼不能用 view.getMeasuredHeight()

這是最關鍵的陷阱。ScrollView 的 getMeasuredHeight() 回傳的是它自己的高度(1038),而不是內容的高度。用它來跟 scrollY + height 比較,等號會在捲動一開始就成立,於是「到底」的訊息被瘋狂觸發。

內容的高度必須從它的直接子 View 取得。這是因為 ScrollView 只允許一個 child,那個 child 的 measured height 就是可捲動的總長度。

return false 的重要性

onTouch 回傳 false,代表「我處理不完,請繼續往下傳」。ScrollView 自身的捲動邏輯依賴接收完整的觸摸事件序列,若回傳 true,事件就被攔截,畫面會變得無法滑動。這裡只是「旁聽」事件做判斷,所以必須回 false。

更推薦的做法

用 OnTouchListener 做檢測有幾個缺點:ACTION_MOVE 會在滑動過程中觸發非常多次,容易產生大量 log 與不必要的判斷;而且它無法涵蓋「用程式呼叫 scrollTo() 造成的位置變化」。

方案 A:覆寫 ScrollView

繼承 ScrollView 並覆寫 onScrollChanged(),它在每次捲動位置改變時被呼叫,比 onTouch 精準且觸發次數合理:

public class ObservableScrollView extends ScrollView {

    public interface OnScrollListener {
        void onScrollChanged(int x, int y, int oldX, int oldY);
    }

    private OnScrollListener listener;

    public void setOnScrollListener(OnScrollListener l) {
        this.listener = l;
    }

    @Override
    protected void onScrollChanged(int x, int y, int oldX, int oldY) {
        super.onScrollChanged(x, y, oldX, oldY);
        if (listener != null) {
            listener.onScrollChanged(x, y, oldX, oldY);
        }
    }

    public boolean isAtTop() {
        return getScrollY() == 0;
    }

    public boolean isAtBottom() {
        View child = getChildAt(0);
        return child != null
                && child.getMeasuredHeight() <= getHeight() + getScrollY();
    }
}

方案 B:改用 NestedScrollView

API 21 之後的 NestedScrollView 支援嵌套捲動,並提供 setOnScrollChangeListener(),不必自己繼承:

nestedScrollView.setOnScrollChangeListener(
        (NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY,
                oldScrollX, oldScrollY) -> {
            View child = v.getChildAt(v.getChildCount() - 1);
            if (scrollY == 0) {
                // 到頂
            } else if (child != null
                    && child.getMeasuredHeight() <= v.getHeight() + scrollY) {
                // 到底
            }
        });

方案 C: RecyclerView 的滾動監聽器

若清單本身就是列表,直接用 RecyclerView 更合適:

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView rv, int dx, int dy) {
        GridLayoutManager lm = (GridLayoutManager) rv.getLayoutManager();
        int total = lm.getItemCount();
        int last = lm.findLastVisibleItemPosition();
        if (last >= 0 && last == total - 1) {
            // 到底了,載入下一頁
        }
    }
});

實務上通常還會加上「距離底部多少」的門檻(例如剩 5 項時就預先載入),讓使用者感覺不到等待。

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