สร้างภาพเคลื่อนไหวการเลื่อนสัมผัส

ลองใช้ Compose
Jetpack Compose เป็นชุดเครื่องมือ UI ที่แนะนำสำหรับ Android ดูวิธีใช้การสัมผัสและการป้อนข้อมูลใน Compose

ใน Android โดยปกติแล้วการเลื่อนจะทำได้โดยใช้คลาส ScrollView ซ้อนเลย์เอาต์มาตรฐานที่อาจขยายเกินขอบเขตของคอนเทนเนอร์ใน ScrollView เพื่อให้มุมมองที่เลื่อนได้ซึ่งจัดการโดยเฟรมเวิร์ก การใช้ตัวเลื่อนที่กำหนดเองจำเป็นสำหรับสถานการณ์พิเศษเท่านั้น เอกสารนี้อธิบายวิธีแสดงเอฟเฟกต์การเลื่อนเพื่อตอบสนอง ต่อท่าทางสัมผัสโดยใช้ scroller

แอปของคุณสามารถใช้ Scroller - Scroller หรือ OverScroller - เพื่อ รวบรวมข้อมูลที่จำเป็นในการสร้างภาพเคลื่อนไหวการเลื่อนเพื่อตอบสนองต่อเหตุการณ์ การแตะ ซึ่งมีความคล้ายกัน แต่ OverScroller ยังมีเมธอดสำหรับ ระบุให้ผู้ใช้ทราบเมื่อเลื่อนหรือปัด ท่าทางสัมผัสจนถึงขอบของเนื้อหา

  • ตั้งแต่ Android 12 (API ระดับ 31) เป็นต้นไป องค์ประกอบภาพจะยืดและดีดกลับ ในเหตุการณ์การลาก และจะดีดกลับในเหตุการณ์การปัด
  • ใน Android 11 (API ระดับ 30) และเวอร์ชันก่อนหน้า ขอบเขตจะแสดงเอฟเฟกต์ "เรืองแสง" หลังจากท่าทางสัมผัสการลากหรือปัดไปที่ขอบ

InteractiveChartตัวอย่างในเอกสารนี้ใช้ EdgeEffect คลาสเพื่อแสดงเอฟเฟกต์การเลื่อนเกินเหล่านี้

คุณใช้ตัวเลื่อนเพื่อเคลื่อนไหวการเลื่อนเมื่อเวลาผ่านไปได้ โดยใช้ ฟิสิกส์การเลื่อนมาตรฐานของแพลตฟอร์ม เช่น แรงเสียดทาน ความเร็ว และคุณภาพอื่นๆ ตัวเลื่อนเองไม่ได้วาดอะไร Scroller จะติดตามออฟเซ็ตการเลื่อน ให้คุณเมื่อเวลาผ่านไป แต่จะไม่ใช้ตำแหน่งเหล่านั้นกับ มุมมองของคุณโดยอัตโนมัติ คุณต้องรับและใช้พิกัดใหม่ในอัตราที่ทำให้ ภาพเคลื่อนไหวของการเลื่อนดูราบรื่น

ทำความเข้าใจคำศัพท์เกี่ยวกับการเลื่อน

การเลื่อนเป็นคำที่อาจมีความหมายแตกต่างกันใน Android ขึ้นอยู่กับบริบท

การเลื่อนคือกระบวนการทั่วไปในการเลื่อนวิวพอร์ต ซึ่งก็คือ "หน้าต่าง" ของเนื้อหาที่คุณกำลังดู เมื่อเลื่อนทั้งในแกนx และแกนy จะเรียกว่าการแพน InteractiveChartแอปตัวอย่างในเอกสารนี้แสดงการเลื่อน 2 ประเภทที่แตกต่างกัน ได้แก่ การลากและการปัด

  • การลาก: เป็นการเลื่อนประเภทหนึ่งที่เกิดขึ้นเมื่อผู้ใช้ ลากนิ้วผ่านหน้าจอสัมผัส คุณสามารถใช้การลากได้โดย การลบล้าง onScroll() ใน GestureDetector.OnGestureListener ดูข้อมูลเพิ่มเติมเกี่ยวกับการลากได้ที่ ลากและปรับขนาด
  • การปัด: เป็นการเลื่อนประเภทหนึ่งที่เกิดขึ้นเมื่อผู้ใช้ ลากและยกนิ้วขึ้นอย่างรวดเร็ว หลังจากผู้ใช้ปล่อยนิ้วแล้ว โดยทั่วไปคุณ ต้องการให้ Viewport เคลื่อนที่ต่อไป แต่ให้ลดความเร็วลงจนกว่า Viewport จะหยุดเคลื่อนที่ คุณสามารถใช้การปัดได้โดยการลบล้าง onFling() ใน GestureDetector.OnGestureListener และใช้ออบเจ็กต์ Scroller
  • การแพน: การเลื่อนพร้อมกันทั้งแกน x และแกน y เรียกว่าการแพน

โดยทั่วไปแล้วมักจะใช้ออบเจ็กต์ Scroller ร่วมกับท่าทางสัมผัสการปัด แต่คุณสามารถใช้ในบริบทใดก็ได้ที่ต้องการให้ 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() calls postInvalidateOnAnimation(), จะทริกเกอร์ computeScroll() เพื่ออัปเดตค่าสำหรับ x และ y โดยปกติจะทำเมื่อ มุมมองย่อยกำลังเคลื่อนไหวการเลื่อนโดยใช้ออบเจ็กต์ Scroller ดังที่แสดงใน ตัวอย่างก่อนหน้า

View ส่วนใหญ่จะส่งตำแหน่ง x และ y ของออบเจ็กต์ Scroller โดยตรง ไปยัง 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% ในทั้ง 2 ทิศทาง ขนาดที่แสดงผลจะใหญ่ขึ้น 2 เท่าในแนวนอนและแนวตั้ง

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()));
}

ดูตัวอย่างการใช้ Scroller อีกตัวอย่างได้ที่ซอร์สโค้ด สำหรับคลาส 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;
      ...
  }
}

ในตัวอย่างก่อนหน้า onInterceptTouchEvent() จะแสดงผล true เมื่อ mIsBeingDragged เป็น 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() ตรงที่ onPullDistance() จะแสดงผล จำนวนที่ใช้ไปของเดลต้าที่ส่งผ่าน ตั้งแต่ Android 12 เป็นต้นไป หากมีการส่งค่าลบ deltaDistanceสำหรับ onPull() หรือ onPullDistance() เมื่อ getDistance() เป็น 0 เอฟเฟกต์การยืดจะไม่เปลี่ยนแปลง ใน Android 11 และเวอร์ชันก่อนหน้า onPull() จะอนุญาตให้ค่าลบสำหรับระยะทางทั้งหมด แสดงเอฟเฟกต์เรืองแสง

เลือกไม่ใช้การเลื่อนเกินขอบเขต

คุณเลือกไม่ใช้การเลื่อนเกินขอบเขตได้ในไฟล์เลย์เอาต์หรือแบบเป็นโปรแกรม

หากต้องการเลือกไม่ใช้ในไฟล์เลย์เอาต์ ให้ตั้งค่า android:overScrollMode ตามที่แสดงในตัวอย่างต่อไปนี้

<MyCustomView android:overScrollMode="never">
    ...
</MyCustomView>

หากต้องการเลือกไม่ใช้แบบเป็นโปรแกรม ให้ใช้โค้ดต่อไปนี้

Kotlin

customView.overScrollMode = View.OVER_SCROLL_NEVER

Java

customView.setOverScrollMode(View.OVER_SCROLL_NEVER);

แหล่งข้อมูลเพิ่มเติม

ดูแหล่งข้อมูลที่เกี่ยวข้องต่อไปนี้