אנימציה של תנועת גלילה

רוצה לנסות את שיטת הכתיבה?
'Jetpack פיתוח נייטיב' היא ערכת הכלים המומלצת לממשק המשתמש ל-Android. מידע נוסף על שימוש בנגיעה ובקלט במהלך 'כתיבה'.

ב-Android, הגלילה בדרך כלל מתבצעת באמצעות ScrollView בכיתה. להציב כל פריסה רגילה שעלולה להתרחב מעבר לגבולות שלה קונטיינר ב-ScrollView כדי לספק תצוגה ניתנת לגלילה שמנוהלת על ידי את המסגרת. הטמעה של פס גלילה מותאם אישית נדרשת רק במקרים מסוימים. במסמך הזה מוסבר איך להציג אפקט גלילה בתגובה למחוות מגע באמצעות גלילה.

האפליקציה שלך יכולה להשתמש גוללים בדף – Scroller או OverScroller עד איסוף הנתונים הדרושים ליצירת אנימציית גלילה בתגובה למגע אירוע. הם דומים, אבל OverScroller כולל גם שיטות להשגת שמציינת למשתמשים כשהם מגיעים לקצוות התוכן לאחר הזזה או הנפה תנועה.

  • החל מ-Android 12 (רמת API 31), הרכיבים החזותיים נמתחים וחוזרים בחזרה לאירוע גרירה, להחליק ולהתאושש מאירוע של הנפה.
  • בגרסה Android 11 (רמת API 30) ובגרסאות קודמות, הגבולות מוצגים עם המילה 'glow' (זוהר). אפקט לאחר תנועת גרירה או החלקה אל הקצה.

הדוגמה InteractiveChart במסמך הזה מתבססת על EdgeEffect כדי להציג את האפקטים של גלילת יתר.

ניתן להשתמש בגלילה כדי להנפיש את הגלילה לאורך זמן, באמצעות פיזיקת גלילה בתקן פלטפורמה, כגון חיכוך, מהירות ועוד איכויות. הגלילה עצמה לא משרטטת דבר. גלילה בין רצועות של כלי גלילה קיימים מבחינתכם לאורך זמן, אבל הם לא מחילים את המיקומים האלה באופן אוטומטי בתצוגה שלכם. עליכם לקבל ולהחיל קואורדינטות חדשות בקצב שיגרום אנימציית גלילה חלקה.

הסבר על טרמינולוגיה של גלילה

לגלילה היא מילה שיכולות להיות לה כמה משמעויות שונות ב-Android, בהתאם את ההקשר.

גלילה היא התהליך הכללי של שינוי אזור התצוגה, כלומר ה"חלון" של התוכן שאתם צופים בו. כשהגלילה מתבצעת בשני הפנים הציר x ו-y נקרא הזזה. אפליקציה אחת (InteractiveChart) לדוגמה במסמך הזה ממחישה שתיים סוגים שונים של גלילה, גרירה והזזה:

  • גרירה: סוג הגלילה שמתרחש כשמשתמש גורר את האצבע על מסך המגע. ניתן לבצע גרירה באמצעות עקיפה onScroll() באזור GestureDetector.OnGestureListener. למידע נוסף על גרירה, אפשר לעיין במאמר גוררים ומשנים קנה מידה.
  • מתרחבת: סוג הגלילה שמתרחש כשמשתמש גורר ומרים את האצבע במהירות. אחרי שהמשתמש מרים את האצבע, בדרך כלל רוצים להמשיך להזיז את אזור התצוגה, אבל להאט עד אזור התצוגה מפסיק לזוז. אפשר להטמיע גרירה על ידי עקיפת onFling() ב-GestureDetector.OnGestureListener ומשתמשים בגלילה לאובייקט.
  • הזזה: גלילה בו-זמנית לאורך הסימן x ו- הצירים y נקראים הזזה.

מקובל להשתמש באובייקטים של גלילה בשילוב עם תנועת הזזה, להשתמש בהם בכל הקשר שבו רוצים שממשק המשתמש יציג גלילה. תגובה לאירוע מגע. לדוגמה, אפשר לשנות את onTouchEvent() כדי לעבד אירועי מגע ישירות וליצור אפקט גלילה 'Snap-to-page' אנימציה בתגובה לאירועי המגע האלה.

רכיבים שכוללים הטמעות גלילה מובְנות

רכיבי 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() כדי לעדכן את הערכים של 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);
}

זוהי ה-method 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;
      ...
  }
}

בדוגמה הקודמת, הפונקציה 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() מחזירה את שנצרכת מתוך הדלתא שהועברה. החל מ-Android 12, אם onPull() או onPullDistance() הועברו כערך שלילי deltaDistance ערכים כאשר 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);

מקורות מידע נוספים

כדאי לעיין במקורות המידע שקשורים לנושא: