以動畫方式呈現捲動手勢

嘗試 Compose 方法
Jetpack Compose 是 Android 推薦的 UI 工具包。瞭解如何在 Compose 中使用觸控和輸入功能。

在 Android 中,通常可透過 ScrollView 類別完成捲動。為所有可能超出 ScrollView 容器邊界的標準版面配置建立巢狀結構,藉此提供由架構管理的可捲動檢視畫面。只有特殊情境才需要實作自訂捲動工具。本文件說明如何使用捲動工具顯示捲動效果,以回應觸控手勢。

應用程式可以使用捲動工具 (ScrollerOverScroller),收集產生捲動動畫所需的資料,以回應觸控事件。兩者相似,但 OverScroller 也包含方法,可在使用者平移或快速滑過手勢後抵達內容邊緣時,發出通知。

  • 從 Android 12 (API 級別 31) 開始,視覺元素會在拖曳事件時延展並彈回,並在快速滑過事件時快速滑過並彈回。
  • 在 Android 11 (API 級別 30) 以下版本中,在對邊緣拖曳或快速滑過手勢後,邊界會顯示「光暈」效果。

本文件中的 InteractiveChart 範例使用 EdgeEffect 類別顯示這些過度捲動效果。

您可以使用捲動器,使用平台標準捲動物理效果 (例如摩擦、速率和其他品質) 隨著捲動的動畫產生動畫效果。捲軸本身沒有繪製任何內容。捲動器會長期追蹤捲動位移,但不會自動將這些位置套用至檢視區塊。您必須以適當的速率取得並套用新座標,讓捲動動畫的呈現更順暢。

瞭解捲動術語

捲動這個字詞在 Android 中可能有不同涵義,具體視情境而定。

「捲動」是移動可視區域的一般程序,也就是您所查看內容的「視窗」。捲動同時在 xy 軸上,稱為「panning」。本文件中的 InteractiveChart 範例應用程式說明兩種不同的捲動、拖曳和快速滑過功能:

  • 拖曳:這是使用者用手指在觸控螢幕上拖曳時會發生的捲動類型。如要實作拖曳功能,您可以覆寫 GestureDetector.OnGestureListener 中的 onScroll()。如要進一步瞭解拖曳功能,請參閱「拖曳與縮放」。
  • 快速滑過:這是使用者快速拖曳並放開手指時會執行的捲動類型。使用者抬起手指後,通常會想要繼續移動可視區域,但慢慢減少,直到可視區域停止移動為止。如要實作快速滑過,您可以覆寫 GestureDetector.OnGestureListener 中的 onFling(),並使用捲動器物件。
  • 平移:xy 軸上同時捲動,稱為「平移」

捲動器物件通常會與快速滑過手勢搭配使用,但您可以在任何想讓 UI 顯示捲動以回應觸控事件的情況下使用這些物件。舉例來說,您可以覆寫 onTouchEvent() 以直接處理觸控事件,並產生捲動效果或「貼齊分頁」動畫,以回應這些觸控事件。

包含內建捲動實作的元件

下列 Android 元件內建支援捲動和過度捲動行為:

如果您的應用程式需要支援在不同元件中的捲動和過度捲動,請完成下列步驟:

  1. 建立自訂以觸控為基礎的捲動實作
  2. 如要支援搭載 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() 來更新 xy 的值。通常在檢視畫面子項使用捲動器物件建立捲動動畫時 (如上例所示)。

多數檢視畫面會將捲軸物件的 xy 位置直接傳遞至 scrollTo()。下列 computeScroll() 實作方法不同:呼叫 computeScrollOffset() 以取得 xy 目前的位置。符合顯示過度捲動「光暈」邊緣效果的條件時,也就是螢幕會放大,xy 不在邊界內,而且應用程式尚未顯示過度捲動,程式碼會設定過度捲動光暈效果,並呼叫 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 類別的原始碼。這類元件會根據快速滑過動作捲動,並使用捲動功能導入「貼齊頁面」動畫。

實作延展過度捲動效果

從 Android 12 開始,EdgeEffect 新增了下列 API,用於實作延展過度捲動效果:

  • getDistance()
  • onPullDistance()

為了提供最佳延展過度捲動的使用者體驗,請執行下列步驟:

  1. 當使用者輕觸內容時,伸展動畫效果時,請將觸控註冊為「檔案」。使用者停止動畫,然後再次開始動作。
  2. 當使用者將手指往反方向移動時,鬆開伸展直到完全消失為止,然後開始捲動。
  3. 使用者在伸展期間快速滑過 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;
      ...
  }
}

在上述範例中,當 mIsBeingDraggedtrueonInterceptTouchEvent() 會傳回 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 起,如果 onPull()onPullDistance()getDistance()0 時傳遞負的 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);

其他資源

請參閱下列相關資源: