在項目中需要監聽ScrollView滑動到頂端和底端的時候以實現自己的ScrollView,那麼怎樣去監聽呢?今天查看了一下ScrollView的源碼,找到了一種方法。先看一下源碼中的overScrollBy()方法:
復制代碼
1 protected boolean overScrollBy(int deltaX, int deltaY,
2 int scrollX, int scrollY,
3 int scrollRangeX, int scrollRangeY,
4 int maxOverScrollX, int maxOverScrollY,
5 boolean isTouchEvent) {
6 final int overScrollMode = mOverScrollMode;
7 final boolean canScrollHorizontal =
8 computeHorizontalScrollRange() > computeHorizontalScrollExtent();
9 final boolean canScrollVertical =
10 computeVerticalScrollRange() > computeVerticalScrollExtent();
11 final boolean overScrollHorizontal = overScrollMode == OVER_SCROLL_ALWAYS ||
12 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollHorizontal);
13 final boolean overScrollVertical = overScrollMode == OVER_SCROLL_ALWAYS ||
14 (overScrollMode == OVER_SCROLL_IF_CONTENT_SCROLLS && canScrollVertical);
15 int newScrollX = scrollX + deltaX;
16 if (!overScrollHorizontal) {
17 maxOverScrollX = 0;
18 }
19 int newScrollY = scrollY + deltaY;
20 if (!overScrollVertical) {
21 maxOverScrollY = 0;
22 }
23 // Clamp values if at the limits and record
24 final int left = -maxOverScrollX;
25 final int right = maxOverScrollX + scrollRangeX;
26 final int top = -maxOverScrollY;
27 final int bottom = maxOverScrollY + scrollRangeY;
28 boolean clampedX = false;
29 if (newScrollX > right) {
30 newScrollX = right;
31 clampedX = true;
32 } else if (newScrollX < left) {
33 newScrollX = left;
34 clampedX = true;
35 }
36 boolean clampedY = false;
37 if (newScrollY > bottom) {
38 newScrollY = bottom;
39 clampedY = true;
40 } else if (newScrollY < top) {
41 newScrollY = top;
42 clampedY = true;
43 }
44 onOverScrolled(newScrollX, newScrollY, clampedX, clampedY);
45 return clampedX || clampedY;
46 }
復制代碼
此方法有9個參數,參數太多有點讓人模糊。這裡我們不管他們是什麼意思,直接看36-43行代碼,很顯然這是一個垂直方向的邊界檢查,而這也正是我們想要的。因此我們可以重寫此方法,在此方法中實現監聽,代碼如下:
復制代碼
1 @Override
2 protected boolean overScrollBy(int deltaX, int deltaY, int scrollX, int scrollY, int scrollRangeX, int scrollRangeY, int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
3
4 int newScrollY = scrollY + deltaY;
5 final int bottom = maxOverScrollY + scrollRangeY;
6 final int top = -maxOverScrollY;
7 if (newScrollY > bottom) {
8 System.out.println("滑動到底端");
9 }
10 else if (newScrollY < top) {
11 System.out.println("滑動到頂端");
12 }
13 return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX, scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
14 }