在 Android 中,捲動作業通常是使用 ScrollView
類別來達成。請在 ScrollView
中 Nest 任何可能會超出容器邊界的標準版面配置,以提供由架構管理的可捲動檢視畫面。只有特殊情境需要導入自訂捲軸。本文件說明如何使用捲動式,在回應觸控手勢時顯示捲動效果。
應用程式可以使用捲動器 (Scroller
或 OverScroller
),收集產生捲動動畫所需的資料,以回應觸控事件。兩者相似,但 OverScroller
也包含一些方法,可在使用者以平移或快速滑過手勢抵達內容邊緣時,向他們顯示提示。
- 從 Android 12 (API 級別 31) 開始,在發生拖曳事件和快速滑過事件時,視覺元素延展並彈回。
- 在 Android 11 (API 級別 30) 以下版本中,當使用者將手勢拖曳到邊緣時,邊界會顯示「發光」效果。
本文件中的 InteractiveChart
範例使用 EdgeEffect
類別來顯示這些過度捲動效果。
您可以使用捲動器,透過執行操作的平台標準捲動物理操作 (例如摩擦、速度和其他性質),在一段時間內以動畫方式捲動捲動。捲動器本身不會繪製任何項目。捲動器會隨著時間追蹤捲動偏移,但不會自動將這些位置套用至檢視畫面。您必須取得並套用新座標,讓捲動動畫保持流暢。
瞭解捲動相關術語
捲動是 Android 系統根據情境說明的意思。
捲動是移動可視區域的一般程序,也就是您正在查看的內容「視窗」。如果捲動位於 x 和 y 軸,則稱為「panning」。本文件中的 InteractiveChart
範例應用程式說明兩種不同的捲動、拖曳和快速滑過類型:
- 拖曳:使用者將手指放在觸控螢幕上時,會發生捲動的類型。如要實作拖曳功能,可以覆寫
GestureDetector.OnGestureListener
中的onScroll()
。如要進一步瞭解如何拖曳,請參閱「拖曳及縮放」。 - 快速滑過:使用者快速拖曳手指時觸發的捲動類型。使用者抬起手指後,通常會希望持續移動可視區域,但請加快速度,直到可視區域停止移動為止。如要實作快速滑過功能,可以覆寫
GestureDetector.OnGestureListener
中的onFling()
,並使用捲動器物件。 - 平移:在「x」和「y」軸上同時捲動稱為「平移」。
我們通常會將捲動器物件與快速滑過手勢搭配使用,但您可以在任何情況下,讓 UI 根據觸控事件顯示捲動畫面,而使用這些物件。舉例來說,您可以覆寫 onTouchEvent()
直接處理觸控事件,並產生捲動效果或「snap-to-page」動畫來回應這些觸控事件。
包含內建捲動實作的元件
下列 Android 元件內建支援捲動和過度捲動行為的功能:
GridView
HorizontalScrollView
ListView
NestedScrollView
RecyclerView
ScrollView
ViewPager
ViewPager2
如果應用程式需要在其他元件內支援捲動及過度捲動功能,請完成下列步驟:
- 建立自訂以觸控為基礎的捲動實作。
- 如要支援搭載 Android 12 以上版本的裝置,請實作延展過度捲動效果。
建立自訂的觸控式捲動實作
本節說明如果應用程式使用的元件未內建支援捲動和過度捲動的元件,該如何建立自己的捲動器。
下列程式碼片段取自 InteractiveChart
範例。這會使用 GestureDetector
並覆寫 GestureDetector.SimpleOnGestureListener
方法 onFling()
。並使用 OverScroller
追蹤快速滑過手勢。如果使用者在執行快速滑過手勢後到達內容邊緣,容器會指出使用者何時抵達內容結尾。該指標會因裝置執行的 Android 版本而異:
- 在 Android 12 以上版本中,視覺元素會延展並返回。
- 在 Android 11 以下版本中,視覺元素會顯示發光效果。
以下程式碼片段的第一部分顯示 onFling()
的實作:
Kotlin
// Viewport extremes. See currentViewport for a discussion of the viewport. private val AXIS_X_MIN = -1f private val AXIS_X_MAX = 1f private val AXIS_Y_MIN = -1f private val AXIS_Y_MAX = 1f // The current viewport. This rectangle represents the visible chart // domain and range. The viewport is the part of the app that the // user manipulates via touch gestures. private val currentViewport = RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX) // The current destination rectangle—in pixel coordinates—into which // the chart data must be drawn. private lateinit var contentRect: Rect private lateinit var scroller: OverScroller private lateinit var scrollerStartViewport: RectF ... private val gestureListener = object : GestureDetector.SimpleOnGestureListener() { override fun onDown(e: MotionEvent): Boolean { // Initiates the decay phase of any active edge effects. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { releaseEdgeEffects() } scrollerStartViewport.set(currentViewport) // Aborts any active scroll animations and invalidates. scroller.forceFinished(true) ViewCompat.postInvalidateOnAnimation(this@InteractiveLineGraphView) return true } ... override fun onFling( e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { fling((-velocityX).toInt(), (-velocityY).toInt()) return true } } private fun fling(velocityX: Int, velocityY: Int) { // Initiates the decay phase of any active edge effects. // On Android 12 and later, the edge effect (stretch) must // continue. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { releaseEdgeEffects() } // Flings use math in pixels, as opposed to math based on the viewport. val surfaceSize: Point = computeScrollSurfaceSize() val (startX: Int, startY: Int) = scrollerStartViewport.run { set(currentViewport) (surfaceSize.x * (left - AXIS_X_MIN) / (AXIS_X_MAX - AXIS_X_MIN)).toInt() to (surfaceSize.y * (AXIS_Y_MAX - bottom) / (AXIS_Y_MAX - AXIS_Y_MIN)).toInt() } // Before flinging, stops the current animation. scroller.forceFinished(true) // Begins the animation. scroller.fling( // Current scroll position. startX, startY, velocityX, velocityY, /* * Minimum and maximum scroll positions. The minimum scroll * position is generally 0 and the maximum scroll position * is generally the content size less the screen size. So if the * content width is 1000 pixels and the screen width is 200 * pixels, the maximum scroll offset is 800 pixels. */ 0, surfaceSize.x - contentRect.width(), 0, surfaceSize.y - contentRect.height(), // The edges of the content. This comes into play when using // the EdgeEffect class to draw "glow" overlays. contentRect.width() / 2, contentRect.height() / 2 ) // Invalidates to trigger computeScroll(). ViewCompat.postInvalidateOnAnimation(this) }
Java
// Viewport extremes. See currentViewport for a discussion of the viewport. private static final float AXIS_X_MIN = -1f; private static final float AXIS_X_MAX = 1f; private static final float AXIS_Y_MIN = -1f; private static final float AXIS_Y_MAX = 1f; // The current viewport. This rectangle represents the visible chart // domain and range. The viewport is the part of the app that the // user manipulates via touch gestures. private RectF currentViewport = new RectF(AXIS_X_MIN, AXIS_Y_MIN, AXIS_X_MAX, AXIS_Y_MAX); // The current destination rectangle—in pixel coordinates—into which // the chart data must be drawn. private final Rect contentRect = new Rect(); private final OverScroller scroller; private final RectF scrollerStartViewport = new RectF(); // Used only for zooms and flings. ... private final GestureDetector.SimpleOnGestureListener gestureListener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { releaseEdgeEffects(); } scrollerStartViewport.set(currentViewport); scroller.forceFinished(true); ViewCompat.postInvalidateOnAnimation(InteractiveLineGraphView.this); return true; } ... @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { fling((int) -velocityX, (int) -velocityY); return true; } }; private void fling(int velocityX, int velocityY) { // Initiates the decay phase of any active edge effects. // On Android 12 and later, the edge effect (stretch) must // continue. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) { releaseEdgeEffects(); } // Flings use math in pixels, as opposed to math based on the viewport. Point surfaceSize = computeScrollSurfaceSize(); scrollerStartViewport.set(currentViewport); int startX = (int) (surfaceSize.x * (scrollerStartViewport.left - AXIS_X_MIN) / ( AXIS_X_MAX - AXIS_X_MIN)); int startY = (int) (surfaceSize.y * (AXIS_Y_MAX - scrollerStartViewport.bottom) / ( AXIS_Y_MAX - AXIS_Y_MIN)); // Before flinging, stops the current animation. scroller.forceFinished(true); // Begins the animation. scroller.fling( // Current scroll position. startX, startY, velocityX, velocityY, /* * Minimum and maximum scroll positions. The minimum scroll * position is generally 0 and the maximum scroll position * is generally the content size less the screen size. So if the * content width is 1000 pixels and the screen width is 200 * pixels, the maximum scroll offset is 800 pixels. */ 0, surfaceSize.x - contentRect.width(), 0, surfaceSize.y - contentRect.height(), // The edges of the content. This comes into play when using // the EdgeEffect class to draw "glow" overlays. contentRect.width() / 2, contentRect.height() / 2); // Invalidates to trigger computeScroll(). ViewCompat.postInvalidateOnAnimation(this); }
當 onFling()
呼叫 postInvalidateOnAnimation()
時,會觸發 computeScroll()
來更新 x 和 y 的值。當檢視畫面子項使用捲動器物件為捲動建立動畫效果時,通常就會這麼做,如以上範例所示。
大多數檢視畫面會將捲動器物件的 x 和 y 位置直接傳遞至 scrollTo()
。以下 computeScroll()
實作的方法不同:它會呼叫 computeScrollOffset()
來取得 x 和 y 的目前位置。滿足以下條件:符合過度捲動「光暈」邊緣效果 (也就是畫面放大,x 或 y 超出邊界),且應用程式並未顯示過度捲動;程式碼會設定過度捲動光暈,並呼叫 postInvalidateOnAnimation()
來觸發檢視畫面失效。
Kotlin
// Edge effect/overscroll tracking objects. private lateinit var edgeEffectTop: EdgeEffect private lateinit var edgeEffectBottom: EdgeEffect private lateinit var edgeEffectLeft: EdgeEffect private lateinit var edgeEffectRight: EdgeEffect private var edgeEffectTopActive: Boolean = false private var edgeEffectBottomActive: Boolean = false private var edgeEffectLeftActive: Boolean = false private var edgeEffectRightActive: Boolean = false override fun computeScroll() { super.computeScroll() var needsInvalidate = false // The scroller isn't finished, meaning a fling or // programmatic pan operation is active. if (scroller.computeScrollOffset()) { val surfaceSize: Point = computeScrollSurfaceSize() val currX: Int = scroller.currX val currY: Int = scroller.currY val (canScrollX: Boolean, canScrollY: Boolean) = currentViewport.run { (left > AXIS_X_MIN || right < AXIS_X_MAX) to (top > AXIS_Y_MIN || bottom < AXIS_Y_MAX) } /* * If you are zoomed in, currX or currY is * outside of bounds, and you aren't already * showing overscroll, then render the overscroll * glow edge effect. */ if (canScrollX && currX < 0 && edgeEffectLeft.isFinished && !edgeEffectLeftActive) { edgeEffectLeft.onAbsorb(scroller.currVelocity.toInt()) edgeEffectLeftActive = true needsInvalidate = true } else if (canScrollX && currX > surfaceSize.x - contentRect.width() && edgeEffectRight.isFinished && !edgeEffectRightActive) { edgeEffectRight.onAbsorb(scroller.currVelocity.toInt()) edgeEffectRightActive = true needsInvalidate = true } if (canScrollY && currY < 0 && edgeEffectTop.isFinished && !edgeEffectTopActive) { edgeEffectTop.onAbsorb(scroller.currVelocity.toInt()) edgeEffectTopActive = true needsInvalidate = true } else if (canScrollY && currY > surfaceSize.y - contentRect.height() && edgeEffectBottom.isFinished && !edgeEffectBottomActive) { edgeEffectBottom.onAbsorb(scroller.currVelocity.toInt()) edgeEffectBottomActive = true needsInvalidate = true } ... } }
Java
// Edge effect/overscroll tracking objects. private EdgeEffectCompat edgeEffectTop; private EdgeEffectCompat edgeEffectBottom; private EdgeEffectCompat edgeEffectLeft; private EdgeEffectCompat edgeEffectRight; private boolean edgeEffectTopActive; private boolean edgeEffectBottomActive; private boolean edgeEffectLeftActive; private boolean edgeEffectRightActive; @Override public void computeScroll() { super.computeScroll(); boolean needsInvalidate = false; // The scroller isn't finished, meaning a fling or // programmatic pan operation is active. if (scroller.computeScrollOffset()) { Point surfaceSize = computeScrollSurfaceSize(); int currX = scroller.getCurrX(); int currY = scroller.getCurrY(); boolean canScrollX = (currentViewport.left > AXIS_X_MIN || currentViewport.right < AXIS_X_MAX); boolean canScrollY = (currentViewport.top > AXIS_Y_MIN || currentViewport.bottom < AXIS_Y_MAX); /* * If you are zoomed in, currX or currY is * outside of bounds, and you aren't already * showing overscroll, then render the overscroll * glow edge effect. */ if (canScrollX && currX < 0 && edgeEffectLeft.isFinished() && !edgeEffectLeftActive) { edgeEffectLeft.onAbsorb((int)mScroller.getCurrVelocity()); edgeEffectLeftActive = true; needsInvalidate = true; } else if (canScrollX && currX > (surfaceSize.x - contentRect.width()) && edgeEffectRight.isFinished() && !edgeEffectRightActive) { edgeEffectRight.onAbsorb((int)mScroller.getCurrVelocity()); edgeEffectRightActive = true; needsInvalidate = true; } if (canScrollY && currY < 0 && edgeEffectTop.isFinished() && !edgeEffectTopActive) { edgeEffectRight.onAbsorb((int)mScroller.getCurrVelocity()); edgeEffectTopActive = true; needsInvalidate = true; } else if (canScrollY && currY > (surfaceSize.y - contentRect.height()) && edgeEffectBottom.isFinished() && !edgeEffectBottomActive) { edgeEffectRight.onAbsorb((int)mScroller.getCurrVelocity()); edgeEffectBottomActive = true; needsInvalidate = true; } ... }
下方是執行實際縮放的程式碼區段:
Kotlin
lateinit var zoomer: Zoomer val zoomFocalPoint = PointF() ... // If a zoom is in progress—either programmatically // or through double touch—this performs the zoom. if (zoomer.computeZoom()) { val newWidth: Float = (1f - zoomer.currZoom) * scrollerStartViewport.width() val newHeight: Float = (1f - zoomer.currZoom) * scrollerStartViewport.height() val pointWithinViewportX: Float = (zoomFocalPoint.x - scrollerStartViewport.left) / scrollerStartViewport.width() val pointWithinViewportY: Float = (zoomFocalPoint.y - scrollerStartViewport.top) / scrollerStartViewport.height() currentViewport.set( zoomFocalPoint.x - newWidth * pointWithinViewportX, zoomFocalPoint.y - newHeight * pointWithinViewportY, zoomFocalPoint.x + newWidth * (1 - pointWithinViewportX), zoomFocalPoint.y + newHeight * (1 - pointWithinViewportY) ) constrainViewport() needsInvalidate = true } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this) }
Java
// Custom object that is functionally similar to Scroller. Zoomer zoomer; private PointF zoomFocalPoint = new PointF(); ... // If a zoom is in progress—either programmatically // or through double touch—this performs the zoom. if (zoomer.computeZoom()) { float newWidth = (1f - zoomer.getCurrZoom()) * scrollerStartViewport.width(); float newHeight = (1f - zoomer.getCurrZoom()) * scrollerStartViewport.height(); float pointWithinViewportX = (zoomFocalPoint.x - scrollerStartViewport.left) / scrollerStartViewport.width(); float pointWithinViewportY = (zoomFocalPoint.y - scrollerStartViewport.top) / scrollerStartViewport.height(); currentViewport.set( zoomFocalPoint.x - newWidth * pointWithinViewportX, zoomFocalPoint.y - newHeight * pointWithinViewportY, zoomFocalPoint.x + newWidth * (1 - pointWithinViewportX), zoomFocalPoint.y + newHeight * (1 - pointWithinViewportY)); constrainViewport(); needsInvalidate = true; } if (needsInvalidate) { ViewCompat.postInvalidateOnAnimation(this); }
這是上述程式碼片段中呼叫的 computeScrollSurfaceSize()
方法。計算目前可捲動的介面大小 (以像素為單位)。舉例來說,如果能看到整個圖表區域,就是目前的 mContentRect
大小。如果圖表往兩個方向縮放 200%,傳回的大小就會是水平和垂直的兩倍。
Kotlin
private fun computeScrollSurfaceSize(): Point { return Point( (contentRect.width() * (AXIS_X_MAX - AXIS_X_MIN) / currentViewport.width()).toInt(), (contentRect.height() * (AXIS_Y_MAX - AXIS_Y_MIN) / currentViewport.height()).toInt() ) }
Java
private Point computeScrollSurfaceSize() { return new Point( (int) (contentRect.width() * (AXIS_X_MAX - AXIS_X_MIN) / currentViewport.width()), (int) (contentRect.height() * (AXIS_Y_MAX - AXIS_Y_MIN) / currentViewport.height())); }
如需其他捲動器使用方式的範例,請參閱 ViewPager
類別的原始碼。這個類別會因應快速滑過來捲動,並使用捲動功能實作「snap-to-page」動畫。
實作延展過度捲動效果
從 Android 12 開始,EdgeEffect
會新增下列 API,用於實作延展過度捲動效果:
getDistance()
onPullDistance()
為提供最佳使用者體驗,您可以利用延展過度捲動功能,請按照下列步驟操作:
- 當使用者觸碰內容時,延展動畫生效時,請將觸控動作註冊為「貓咪」。使用者停止動畫,然後再次開始操縱延展。
- 當使用者用手指往伸展方向移動時,請放開伸展直至完全消失,然後開始捲動。
- 使用者在伸展期間快速滑過時,快速滑過
EdgeEffect
即可強化延展效果。
擷取動畫
當使用者擷取到進行中的延展動畫時,EdgeEffect.getDistance()
會傳回 0
。這個狀況表示延展動作必須受到觸控動作操作。在大多數的容器中,系統會在 onInterceptTouchEvent()
中偵測擷取,如以下程式碼片段所示:
Kotlin
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { ... when (action and MotionEvent.ACTION_MASK) { MotionEvent.ACTION_DOWN -> ... isBeingDragged = EdgeEffectCompat.getDistance(edgeEffectBottom) > 0f || EdgeEffectCompat.getDistance(edgeEffectTop) > 0f ... } return isBeingDragged }
Java
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { ... switch (action & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: ... isBeingDragged = EdgeEffectCompat.getDistance(edgeEffectBottom) > 0 || EdgeEffectCompat.getDistance(edgeEffectTop) > 0; ... } }
在上述範例中,當 mIsBeingDragged
為 true
時,onInterceptTouchEvent()
會傳回 true
,因此在子項有機會使用事件之前,就足以使用該事件。
放開過度捲動效果
請務必在捲動前釋放延展效果,以免延展效果套用至捲動內容。下列程式碼範例適用於這項最佳做法:
Kotlin
override fun onTouchEvent(ev: MotionEvent): Boolean { val activePointerIndex = ev.actionIndex when (ev.getActionMasked()) { MotionEvent.ACTION_MOVE -> val x = ev.getX(activePointerIndex) val y = ev.getY(activePointerIndex) var deltaY = y - lastMotionY val pullDistance = deltaY / height val displacement = x / width if (deltaY < 0f && EdgeEffectCompat.getDistance(edgeEffectTop) > 0f) { deltaY -= height * EdgeEffectCompat.onPullDistance(edgeEffectTop, pullDistance, displacement); } if (deltaY > 0f && EdgeEffectCompat.getDistance(edgeEffectBottom) > 0f) { deltaY += height * EdgeEffectCompat.onPullDistance(edgeEffectBottom, -pullDistance, 1 - displacement); } ... }
Java
@Override public boolean onTouchEvent(MotionEvent ev) { final int actionMasked = ev.getActionMasked(); switch (actionMasked) { case MotionEvent.ACTION_MOVE: final float x = ev.getX(activePointerIndex); final float y = ev.getY(activePointerIndex); float deltaY = y - lastMotionY; float pullDistance = deltaY / getHeight(); float displacement = x / getWidth(); if (deltaY < 0 && EdgeEffectCompat.getDistance(edgeEffectTop) > 0) { deltaY -= getHeight() * EdgeEffectCompat.onPullDistance(edgeEffectTop, pullDistance, displacement); } if (deltaY > 0 && EdgeEffectCompat.getDistance(edgeEffectBottom) > 0) { deltaY += getHeight() * EdgeEffectCompat.onPullDistance(edgeEffectBottom, -pullDistance, 1 - displacement); } ...
當使用者拖曳時,請先消耗 EdgeEffect
提取距離,然後再將觸控事件傳遞至巢狀捲動容器,或拖曳捲動。在上述程式碼範例中,當顯示邊緣效果時,getDistance()
會傳回正值,並能透過動態方式發布。當觸控事件釋放伸展動作時,會先由 EdgeEffect
取用,使它在顯示其他效果之前完全釋放,例如巢狀捲動。您可以使用 getDistance()
瞭解需要多少提取距離才能釋出目前的效果。
與 onPull()
不同,onPullDistance()
會傳回傳遞的差異的耗用量。自 Android 12 起,當 getDistance()
為 0
時,如果 onPull()
或 onPullDistance()
傳遞負值 deltaDistance
值,延展效果不會變更。在 Android 11 以下版本中,onPull()
可讓總距離的負值顯示光暈效果。
停用過度捲動
您可以在版面配置檔案中停用過度捲動功能,或透過程式輔助方式停用。
如要選擇不採用版面配置檔案,請依以下範例設定 android:overScrollMode
:
<MyCustomView android:overScrollMode="never"> ... </MyCustomView>
如要透過程式輔助方式停用,請使用以下程式碼:
Kotlin
customView.overScrollMode = View.OVER_SCROLL_NEVER
Java
customView.setOverScrollMode(View.OVER_SCROLL_NEVER);
其他資源
請參閱下列相關資源: