ViewDragHelper.java revision 1732720ad57fe6d01392cd06551f1a25cff0333c
1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package android.support.v4.widget;
19
20import android.content.Context;
21import android.support.v4.view.MotionEventCompat;
22import android.support.v4.view.VelocityTrackerCompat;
23import android.support.v4.view.ViewCompat;
24import android.view.MotionEvent;
25import android.view.VelocityTracker;
26import android.view.View;
27import android.view.ViewConfiguration;
28import android.view.ViewGroup;
29import android.view.animation.Interpolator;
30
31import java.util.Arrays;
32
33/**
34 * ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number
35 * of useful operations and state tracking for allowing a user to drag and reposition
36 * views within their parent ViewGroup.
37 */
38public class ViewDragHelper {
39    private static final String TAG = "ViewDragHelper";
40
41    /**
42     * A null/invalid pointer ID.
43     */
44    public static final int INVALID_POINTER = -1;
45
46    /**
47     * A view is not currently being dragged or animating as a result of a fling/snap.
48     */
49    public static final int STATE_IDLE = 0;
50
51    /**
52     * A view is currently being dragged. The position is currently changing as a result
53     * of user input or simulated user input.
54     */
55    public static final int STATE_DRAGGING = 1;
56
57    /**
58     * A view is currently settling into place as a result of a fling or
59     * predefined non-interactive motion.
60     */
61    public static final int STATE_SETTLING = 2;
62
63    /**
64     * Edge flag indicating that the left edge should be affected.
65     */
66    public static final int EDGE_LEFT = 1 << 0;
67
68    /**
69     * Edge flag indicating that the right edge should be affected.
70     */
71    public static final int EDGE_RIGHT = 1 << 1;
72
73    /**
74     * Edge flag indicating that the top edge should be affected.
75     */
76    public static final int EDGE_TOP = 1 << 2;
77
78    /**
79     * Edge flag indicating that the bottom edge should be affected.
80     */
81    public static final int EDGE_BOTTOM = 1 << 3;
82
83    /**
84     * Edge flag set indicating all edges should be affected.
85     */
86    public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM;
87
88    /**
89     * Indicates that a check should occur along the horizontal axis
90     */
91    public static final int DIRECTION_HORIZONTAL = 1 << 0;
92
93    /**
94     * Indicates that a check should occur along the vertical axis
95     */
96    public static final int DIRECTION_VERTICAL = 1 << 1;
97
98    /**
99     * Indicates that a check should occur along all axes
100     */
101    public static final int DIRECTION_ALL = DIRECTION_HORIZONTAL | DIRECTION_VERTICAL;
102
103    private static final int EDGE_SIZE = 24; // dp
104
105    private static final int BASE_SETTLE_DURATION = 256; // ms
106    private static final int MAX_SETTLE_DURATION = 600; // ms
107
108    // Current drag state; idle, dragging or settling
109    private int mDragState;
110
111    // Distance to travel before a drag may begin
112    private int mTouchSlop;
113
114    // Last known position/pointer tracking
115    private int mActivePointerId = INVALID_POINTER;
116    private float[] mInitialMotionX;
117    private float[] mInitialMotionY;
118    private float[] mLastMotionX;
119    private float[] mLastMotionY;
120    private int[] mInitialEdgesTouched;
121    private int[] mEdgeDragsInProgress;
122    private int[] mEdgeDragsLocked;
123    private int mPointersDown;
124
125    private VelocityTracker mVelocityTracker;
126    private float mMaxVelocity;
127    private float mMinVelocity;
128
129    private int mEdgeSize;
130    private int mTrackingEdges;
131
132    private ScrollerCompat mScroller;
133
134    private final Callback mCallback;
135
136    private View mCapturedView;
137    private boolean mReleaseInProgress;
138
139    private final ViewGroup mParentView;
140
141    /**
142     * A Callback is used as a communication channel with the ViewDragHelper back to the
143     * parent view using it. <code>on*</code>methods are invoked on siginficant events and several
144     * accessor methods are expected to provide the ViewDragHelper with more information
145     * about the state of the parent view upon request. The callback also makes decisions
146     * governing the range and draggability of child views.
147     */
148    public static abstract class Callback {
149        /**
150         * Called when the drag state changes. See the <code>STATE_*</code> constants
151         * for more information.
152         *
153         * @param state The new drag state
154         *
155         * @see #STATE_IDLE
156         * @see #STATE_DRAGGING
157         * @see #STATE_SETTLING
158         */
159        public void onViewDragStateChanged(int state) {}
160
161        /**
162         * Called when the captured view's position changes as the result of a drag or settle.
163         *
164         * @param changedView View whose position changed
165         * @param left New X coordinate of the left edge of the view
166         * @param top New Y coordinate of the top edge of the view
167         * @param dx Change in X position from the last call
168         * @param dy Change in Y position from the last call
169         */
170        public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {}
171
172        /**
173         * Called when a child view is captured for dragging or settling. The ID of the pointer
174         * currently dragging the captured view is supplied. If activePointerId is
175         * identified as {@link #INVALID_POINTER} the capture is programmatic instead of
176         * pointer-initiated.
177         *
178         * @param capturedChild Child view that was captured
179         * @param activePointerId Pointer id tracking the child capture
180         */
181        public void onViewCaptured(View capturedChild, int activePointerId) {}
182
183        /**
184         * Called when the child view is no longer being actively dragged.
185         * The fling velocity is also supplied, if relevant. The velocity values may
186         * be clamped to system minimums or maximums.
187         *
188         * <p>Calling code may decide to fling or otherwise release the view to let it
189         * settle into place. It should do so using {@link #settleCapturedViewAt(int, int)}
190         * or {@link #flingCapturedView(int, int, int, int)}. If the Callback invokes
191         * one of these methods, the ViewDragHelper will enter {@link #STATE_SETTLING}
192         * and the view capture will not fully end until it comes to a complete stop.
193         * If neither of these methods is invoked before <code>onViewReleased</code> returns,
194         * the view will stop in place and the ViewDragHelper will return to
195         * {@link #STATE_IDLE}.</p>
196         *
197         * @param releasedChild The captured child view now being released
198         * @param xvel X velocity of the pointer as it left the screen in pixels per second.
199         * @param yvel Y velocity of the pointer as it left the screen in pixels per second.
200         */
201        public void onViewReleased(View releasedChild, float xvel, float yvel) {}
202
203        /**
204         * Called when one of the subscribed edges in the parent view has been touched
205         * by the user while no child view is currently captured.
206         *
207         * @param edgeFlags A combination of edge flags describing the edge(s) currently touched
208         * @param pointerId ID of the pointer touching the described edge(s)
209         * @see #EDGE_LEFT
210         * @see #EDGE_TOP
211         * @see #EDGE_RIGHT
212         * @see #EDGE_BOTTOM
213         */
214        public void onEdgeTouched(int edgeFlags, int pointerId) {}
215
216        /**
217         * Called when the given edge may become locked. This can happen if an edge drag
218         * was preliminarily rejected before beginning, but after {@link #onEdgeTouched(int, int)}
219         * was called. This method should return true to lock this edge or false to leave it
220         * unlocked. The default behavior is to leave edges unlocked.
221         *
222         * @param edgeFlags A combination of edge flags describing the edge(s) locked
223         * @return true to lock the edge, false to leave it unlocked
224         */
225        public boolean onEdgeLock(int edgeFlags) {
226            return false;
227        }
228
229        /**
230         * Called when the user has started a deliberate drag away from one
231         * of the subscribed edges in the parent view while no child view is currently captured.
232         *
233         * @param edgeFlags A combination of edge flags describing the edge(s) dragged
234         * @param pointerId ID of the pointer touching the described edge(s)
235         * @see #EDGE_LEFT
236         * @see #EDGE_TOP
237         * @see #EDGE_RIGHT
238         * @see #EDGE_BOTTOM
239         */
240        public void onEdgeDragStarted(int edgeFlags, int pointerId) {}
241
242        /**
243         * Called to determine the Z-order of child views.
244         *
245         * @param index the ordered position to query for
246         * @return index of the view that should be ordered at position <code>index</code>
247         */
248        public int getOrderedChildIndex(int index) {
249            return index;
250        }
251
252        /**
253         * Return the magnitude of a draggable child view's horizontal range of motion in pixels.
254         * This method should return 0 for views that cannot move horizontally.
255         *
256         * @param child Child view to check
257         * @return range of horizontal motion in pixels
258         */
259        public int getViewHorizontalDragRange(View child) {
260            return 0;
261        }
262
263        /**
264         * Return the magnitude of a draggable child view's vertical range of motion in pixels.
265         * This method should return 0 for views that cannot move vertically.
266         *
267         * @param child Child view to check
268         * @return range of vertical motion in pixels
269         */
270        public int getViewVerticalDragRange(View child) {
271            return 0;
272        }
273
274        /**
275         * Called when the user's input indicates that they want to capture the given child view
276         * with the pointer indicated by pointerId. The callback should return true if the user
277         * is permitted to drag the given view with the indicated pointer.
278         *
279         * <p>ViewDragHelper may call this method multiple times for the same view even if
280         * the view is already captured; this indicates that a new pointer is trying to take
281         * control of the view.</p>
282         *
283         * <p>If this method returns true, a call to {@link #onViewCaptured(android.view.View, int)}
284         * will follow if the capture is successful.</p>
285         *
286         * @param child Child the user is attempting to capture
287         * @param pointerId ID of the pointer attempting the capture
288         * @return true if capture should be allowed, false otherwise
289         */
290        public abstract boolean tryCaptureView(View child, int pointerId);
291
292        /**
293         * Restrict the motion of the dragged child view along the horizontal axis.
294         * The default implementation does not allow horizontal motion; the extending
295         * class must override this method and provide the desired clamping.
296         *
297         *
298         * @param child Child view being dragged
299         * @param left Attempted motion along the X axis
300         * @param dx Proposed change in position for left
301         * @return The new clamped position for left
302         */
303        public int clampViewPositionHorizontal(View child, int left, int dx) {
304            return 0;
305        }
306
307        /**
308         * Restrict the motion of the dragged child view along the vertical axis.
309         * The default implementation does not allow vertical motion; the extending
310         * class must override this method and provide the desired clamping.
311         *
312         *
313         * @param child Child view being dragged
314         * @param top Attempted motion along the Y axis
315         * @param dy Proposed change in position for top
316         * @return The new clamped position for top
317         */
318        public int clampViewPositionVertical(View child, int top, int dy) {
319            return 0;
320        }
321    }
322
323    /**
324     * Interpolator defining the animation curve for mScroller
325     */
326    private static final Interpolator sInterpolator = new Interpolator() {
327        public float getInterpolation(float t) {
328            t -= 1.0f;
329            return t * t * t * t * t + 1.0f;
330        }
331    };
332
333    private final Runnable mSetIdleRunnable = new Runnable() {
334        public void run() {
335            setDragState(STATE_IDLE);
336        }
337    };
338
339    /**
340     * Factory method to create a new ViewDragHelper.
341     *
342     * @param forParent Parent view to monitor
343     * @param cb Callback to provide information and receive events
344     * @return a new ViewDragHelper instance
345     */
346    public static ViewDragHelper create(ViewGroup forParent, Callback cb) {
347        return new ViewDragHelper(forParent.getContext(), forParent, cb);
348    }
349
350    /**
351     * Factory method to create a new ViewDragHelper.
352     *
353     * @param forParent Parent view to monitor
354     * @param sensitivity Multiplier for how sensitive the helper should be about detecting
355     *                    the start of a drag. Larger values are more sensitive. 1.0f is normal.
356     * @param cb Callback to provide information and receive events
357     * @return a new ViewDragHelper instance
358     */
359    public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {
360        final ViewDragHelper helper = create(forParent, cb);
361        helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
362        return helper;
363    }
364
365    /**
366     * Apps should use ViewDragHelper.create() to get a new instance.
367     * This will allow VDH to use internal compatibility implementations for different
368     * platform versions.
369     *
370     * @param context Context to initialize config-dependent params from
371     * @param forParent Parent view to monitor
372     */
373    private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) {
374        if (forParent == null) {
375            throw new IllegalArgumentException("Parent view may not be null");
376        }
377        if (cb == null) {
378            throw new IllegalArgumentException("Callback may not be null");
379        }
380
381        mParentView = forParent;
382        mCallback = cb;
383
384        final ViewConfiguration vc = ViewConfiguration.get(context);
385        final float density = context.getResources().getDisplayMetrics().density;
386        mEdgeSize = (int) (EDGE_SIZE * density + 0.5f);
387
388        mTouchSlop = vc.getScaledTouchSlop();
389        mMaxVelocity = vc.getScaledMaximumFlingVelocity();
390        mMinVelocity = vc.getScaledMinimumFlingVelocity();
391        mScroller = ScrollerCompat.create(context, sInterpolator);
392    }
393
394    /**
395     * Retrieve the current drag state of this helper. This will return one of
396     * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
397     * @return The current drag state
398     */
399    public int getViewDragState() {
400        return mDragState;
401    }
402
403    /**
404     * Enable edge tracking for the selected edges of the parent view.
405     * The callback's {@link Callback#onEdgeTouched(int, int)} and
406     * {@link Callback#onEdgeDragStarted(int, int)} methods will only be invoked
407     * for edges for which edge tracking has been enabled.
408     *
409     * @param edgeFlags Combination of edge flags describing the edges to watch
410     * @see #EDGE_LEFT
411     * @see #EDGE_TOP
412     * @see #EDGE_RIGHT
413     * @see #EDGE_BOTTOM
414     */
415    public void setEdgeTrackingEnabled(int edgeFlags) {
416        mTrackingEdges = edgeFlags;
417    }
418
419    /**
420     * Return the size of an edge. This is the range in pixels along the edges of this view
421     * that will actively detect edge touches or drags if edge tracking is enabled.
422     *
423     * @return The size of an edge in pixels
424     * @see #setEdgeTrackingEnabled(int)
425     */
426    public int getEdgeSize() {
427        return mEdgeSize;
428    }
429
430    /**
431     * Capture a specific child view for dragging within the parent. The callback will be notified
432     * but {@link Callback#tryCaptureView(android.view.View, int)} will not be asked permission to
433     * capture this view.
434     *
435     * @param childView Child view to capture
436     * @param activePointerId ID of the pointer that is dragging the captured child view
437     */
438    public void captureChildView(View childView, int activePointerId) {
439        if (childView.getParent() != mParentView) {
440            throw new IllegalArgumentException("captureChildView: parameter must be a descendant " +
441                    "of the ViewDragHelper's tracked parent view (" + mParentView + ")");
442        }
443
444        mCapturedView = childView;
445        mActivePointerId = activePointerId;
446        mCallback.onViewCaptured(childView, activePointerId);
447        setDragState(STATE_DRAGGING);
448    }
449
450    /**
451     * @return The currently captured view, or null if no view has been captured.
452     */
453    public View getCapturedView() {
454        return mCapturedView;
455    }
456
457    /**
458     * @return The ID of the pointer currently dragging the captured view,
459     *         or {@link #INVALID_POINTER}.
460     */
461    public int getActivePointerId() {
462        return mActivePointerId;
463    }
464
465    /**
466     * @return The minimum distance in pixels that the user must travel to initiate a drag
467     */
468    public int getTouchSlop() {
469        return mTouchSlop;
470    }
471
472    /**
473     * The result of a call to this method is equivalent to
474     * {@link #processTouchEvent(android.view.MotionEvent)} receiving an ACTION_CANCEL event.
475     */
476    public void cancel() {
477        mActivePointerId = INVALID_POINTER;
478        clearMotionHistory();
479
480        if (mVelocityTracker != null) {
481            mVelocityTracker.recycle();
482            mVelocityTracker = null;
483        }
484    }
485
486    /**
487     * {@link #cancel()}, but also abort all motion in progress and snap to the end of any
488     * animation.
489     */
490    public void abort() {
491        cancel();
492        if (mDragState == STATE_SETTLING) {
493            final int oldX = mScroller.getCurrX();
494            final int oldY = mScroller.getCurrY();
495            mScroller.abortAnimation();
496            final int newX = mScroller.getCurrX();
497            final int newY = mScroller.getCurrY();
498            mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY);
499        }
500        setDragState(STATE_IDLE);
501    }
502
503    /**
504     * Animate the view <code>child</code> to the given (left, top) position.
505     * If this method returns true, the caller should invoke {@link #continueSettling(boolean)}
506     * on each subsequent frame to continue the motion until it returns false. If this method
507     * returns false there is no further work to do to complete the movement.
508     *
509     * <p>This operation does not count as a capture event, though {@link #getCapturedView()}
510     * will still report the sliding view while the slide is in progress.</p>
511     *
512     * @param child Child view to capture and animate
513     * @param finalLeft Final left position of child
514     * @param finalTop Final top position of child
515     * @return true if animation should continue through {@link #continueSettling(boolean)} calls
516     */
517    public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) {
518        mCapturedView = child;
519        mActivePointerId = INVALID_POINTER;
520
521        return forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0);
522    }
523
524    /**
525     * Settle the captured view at the given (left, top) position.
526     * The appropriate velocity from prior motion will be taken into account.
527     * If this method returns true, the caller should invoke {@link #continueSettling(boolean)}
528     * on each subsequent frame to continue the motion until it returns false. If this method
529     * returns false there is no further work to do to complete the movement.
530     *
531     * @param finalLeft Settled left edge position for the captured view
532     * @param finalTop Settled top edge position for the captured view
533     * @return true if animation should continue through {@link #continueSettling(boolean)} calls
534     */
535    public boolean settleCapturedViewAt(int finalLeft, int finalTop) {
536        if (!mReleaseInProgress) {
537            throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to " +
538                    "Callback#onViewReleased");
539        }
540
541        return forceSettleCapturedViewAt(finalLeft, finalTop,
542                (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
543                (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId));
544    }
545
546    /**
547     * Settle the captured view at the given (left, top) position.
548     *
549     * @param finalLeft Target left position for the captured view
550     * @param finalTop Target top position for the captured view
551     * @param xvel Horizontal velocity
552     * @param yvel Vertical velocity
553     * @return true if animation should continue through {@link #continueSettling(boolean)} calls
554     */
555    private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) {
556        final int startLeft = mCapturedView.getLeft();
557        final int startTop = mCapturedView.getTop();
558        final int dx = finalLeft - startLeft;
559        final int dy = finalTop - startTop;
560
561        if (dx == 0 && dy == 0) {
562            // Nothing to do. Send callbacks, be done.
563            mScroller.abortAnimation();
564            setDragState(STATE_IDLE);
565            return false;
566        }
567
568        final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel);
569        mScroller.startScroll(startLeft, startTop, dx, dy, duration);
570
571        setDragState(STATE_SETTLING);
572        return true;
573    }
574
575    private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) {
576        xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity);
577        yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity);
578        final int absDx = Math.abs(dx);
579        final int absDy = Math.abs(dy);
580        final int absXVel = Math.abs(xvel);
581        final int absYVel = Math.abs(yvel);
582        final int addedVel = absXVel + absYVel;
583        final int addedDistance = absDx + absDy;
584
585        final float xweight = xvel != 0 ? (float) absXVel / addedVel :
586                (float) absDx / addedDistance;
587        final float yweight = yvel != 0 ? (float) absYVel / addedVel :
588                (float) absDy / addedDistance;
589
590        int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child));
591        int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child));
592
593        return (int) (xduration * xweight + yduration * yweight);
594    }
595
596    private int computeAxisDuration(int delta, int velocity, int motionRange) {
597        if (delta == 0) {
598            return 0;
599        }
600
601        final int width = mParentView.getWidth();
602        final int halfWidth = width / 2;
603        final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width);
604        final float distance = halfWidth + halfWidth *
605                distanceInfluenceForSnapDuration(distanceRatio);
606
607        int duration;
608        velocity = Math.abs(velocity);
609        if (velocity > 0) {
610            duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
611        } else {
612            final float range = (float) Math.abs(delta) / motionRange;
613            duration = (int) ((range + 1) * BASE_SETTLE_DURATION);
614        }
615        return Math.min(duration, MAX_SETTLE_DURATION);
616    }
617
618    /**
619     * Clamp the magnitude of value for absMin and absMax.
620     * If the value is below the minimum, it will be clamped to zero.
621     * If the value is above the maximum, it will be clamped to the maximum.
622     *
623     * @param value Value to clamp
624     * @param absMin Absolute value of the minimum significant value to return
625     * @param absMax Absolute value of the maximum value to return
626     * @return The clamped value with the same sign as <code>value</code>
627     */
628    private int clampMag(int value, int absMin, int absMax) {
629        final int absValue = Math.abs(value);
630        if (absValue < absMin) return 0;
631        if (absValue > absMax) return value > 0 ? absMax : -absMax;
632        return value;
633    }
634
635    private float distanceInfluenceForSnapDuration(float f) {
636        f -= 0.5f; // center the values about 0.
637        f *= 0.3f * Math.PI / 2.0f;
638        return (float) Math.sin(f);
639    }
640
641    /**
642     * Settle the captured view based on standard free-moving fling behavior.
643     * The caller should invoke {@link #continueSettling(boolean)} on each subsequent frame
644     * to continue the motion until it returns false.
645     *
646     * @param minLeft Minimum X position for the view's left edge
647     * @param minTop Minimum Y position for the view's top edge
648     * @param maxLeft Maximum X position for the view's left edge
649     * @param maxTop Maximum Y position for the view's top edge
650     */
651    public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {
652        if (!mReleaseInProgress) {
653            throw new IllegalStateException("Cannot flingCapturedView outside of a call to " +
654                    "Callback#onViewReleased");
655        }
656
657        mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(),
658                (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
659                (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
660                minLeft, maxLeft, minTop, maxTop);
661
662        setDragState(STATE_SETTLING);
663    }
664
665    /**
666     * Move the captured settling view by the appropriate amount for the current time.
667     * If <code>continueSettling</code> returns true, the caller should call it again
668     * on the next frame to continue.
669     *
670     * @param deferCallbacks true if state callbacks should be deferred via posted message.
671     *                       Set this to true if you are calling this method from
672     *                       {@link android.view.View#computeScroll()} or similar methods
673     *                       invoked as part of layout or drawing.
674     * @return true if settle is still in progress
675     */
676    public boolean continueSettling(boolean deferCallbacks) {
677        if (mDragState == STATE_SETTLING) {
678            boolean keepGoing = mScroller.computeScrollOffset();
679            final int x = mScroller.getCurrX();
680            final int y = mScroller.getCurrY();
681            final int dx = x - mCapturedView.getLeft();
682            final int dy = y - mCapturedView.getTop();
683
684            if (dx != 0) {
685                mCapturedView.offsetLeftAndRight(dx);
686            }
687            if (dy != 0) {
688                mCapturedView.offsetTopAndBottom(dy);
689            }
690
691            if (dx != 0 || dy != 0) {
692                mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
693            }
694
695            if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
696                // Close enough. The interpolator/scroller might think we're still moving
697                // but the user sure doesn't.
698                mScroller.abortAnimation();
699                keepGoing = mScroller.isFinished();
700            }
701
702            if (!keepGoing) {
703                if (deferCallbacks) {
704                    mParentView.post(mSetIdleRunnable);
705                } else {
706                    setDragState(STATE_IDLE);
707                }
708            }
709        }
710
711        return mDragState == STATE_SETTLING;
712    }
713
714    /**
715     * Like all callback events this must happen on the UI thread, but release
716     * involves some extra semantics. During a release (mReleaseInProgress)
717     * is the only time it is valid to call {@link #settleCapturedViewAt(int, int)}
718     * or {@link #flingCapturedView(int, int, int, int)}.
719     */
720    private void dispatchViewReleased(float xvel, float yvel) {
721        mReleaseInProgress = true;
722        mCallback.onViewReleased(mCapturedView, xvel, yvel);
723        mReleaseInProgress = false;
724
725        if (mDragState == STATE_DRAGGING) {
726            // onViewReleased didn't call a method that would have changed this. Go idle.
727            setDragState(STATE_IDLE);
728        }
729    }
730
731    private void clearMotionHistory() {
732        if (mInitialMotionX == null) {
733            return;
734        }
735        Arrays.fill(mInitialMotionX, 0);
736        Arrays.fill(mInitialMotionY, 0);
737        Arrays.fill(mLastMotionX, 0);
738        Arrays.fill(mLastMotionY, 0);
739        Arrays.fill(mInitialEdgesTouched, 0);
740        Arrays.fill(mEdgeDragsInProgress, 0);
741        Arrays.fill(mEdgeDragsLocked, 0);
742        mPointersDown = 0;
743    }
744
745    private void clearMotionHistory(int pointerId) {
746        if (mInitialMotionX == null) {
747            return;
748        }
749        mInitialMotionX[pointerId] = 0;
750        mInitialMotionY[pointerId] = 0;
751        mLastMotionX[pointerId] = 0;
752        mLastMotionY[pointerId] = 0;
753        mInitialEdgesTouched[pointerId] = 0;
754        mEdgeDragsInProgress[pointerId] = 0;
755        mEdgeDragsLocked[pointerId] = 0;
756        mPointersDown &= ~(1 << pointerId);
757    }
758
759    private void ensureMotionHistorySizeForId(int pointerId) {
760        if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) {
761            float[] imx = new float[pointerId + 1];
762            float[] imy = new float[pointerId + 1];
763            float[] lmx = new float[pointerId + 1];
764            float[] lmy = new float[pointerId + 1];
765            int[] iit = new int[pointerId + 1];
766            int[] edip = new int[pointerId + 1];
767            int[] edl = new int[pointerId + 1];
768
769            if (mInitialMotionX != null) {
770                System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length);
771                System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length);
772                System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length);
773                System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length);
774                System.arraycopy(mInitialEdgesTouched, 0, iit, 0, mInitialEdgesTouched.length);
775                System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length);
776                System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length);
777            }
778
779            mInitialMotionX = imx;
780            mInitialMotionY = imy;
781            mLastMotionX = lmx;
782            mLastMotionY = lmy;
783            mInitialEdgesTouched = iit;
784            mEdgeDragsInProgress = edip;
785            mEdgeDragsLocked = edl;
786        }
787    }
788
789    private void saveInitialMotion(float x, float y, int pointerId) {
790        ensureMotionHistorySizeForId(pointerId);
791        mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
792        mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
793        mInitialEdgesTouched[pointerId] = getEdgesTouched((int) x, (int) y);
794        mPointersDown |= 1 << pointerId;
795    }
796
797    private void saveLastMotion(MotionEvent ev) {
798        final int pointerCount = MotionEventCompat.getPointerCount(ev);
799        for (int i = 0; i < pointerCount; i++) {
800            final int pointerId = MotionEventCompat.getPointerId(ev, i);
801            final float x = MotionEventCompat.getX(ev, i);
802            final float y = MotionEventCompat.getY(ev, i);
803            mLastMotionX[pointerId] = x;
804            mLastMotionY[pointerId] = y;
805        }
806    }
807
808    /**
809     * Check if the given pointer ID represents a pointer that is currently down (to the best
810     * of the ViewDragHelper's knowledge).
811     *
812     * <p>The state used to report this information is populated by the methods
813     * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
814     * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these methods has not
815     * been called for all relevant MotionEvents to track, the information reported
816     * by this method may be stale or incorrect.</p>
817     *
818     * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent
819     * @return true if the pointer with the given ID is still down
820     */
821    public boolean isPointerDown(int pointerId) {
822        return (mPointersDown & 1 << pointerId) != 0;
823    }
824
825    void setDragState(int state) {
826        if (mDragState != state) {
827            mDragState = state;
828            mCallback.onViewDragStateChanged(state);
829            if (state == STATE_IDLE) {
830                mCapturedView = null;
831            }
832        }
833    }
834
835    /**
836     * Attempt to capture the view with the given pointer ID. The callback will be involved.
837     * This will put us into the "dragging" state. If we've already captured this view with
838     * this pointer this method will immediately return true without consulting the callback.
839     *
840     * @param toCapture View to capture
841     * @param pointerId Pointer to capture with
842     * @return true if capture was successful
843     */
844    boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
845        if (toCapture == mCapturedView && mActivePointerId == pointerId) {
846            // Already done!
847            return true;
848        }
849        if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
850            mActivePointerId = pointerId;
851            captureChildView(toCapture, pointerId);
852            return true;
853        }
854        return false;
855    }
856
857    /**
858     * Tests scrollability within child views of v given a delta of dx.
859     *
860     * @param v View to test for horizontal scrollability
861     * @param checkV Whether the view v passed should itself be checked for scrollability (true),
862     *               or just its children (false).
863     * @param dx Delta scrolled in pixels along the X axis
864     * @param dy Delta scrolled in pixels along the Y axis
865     * @param x X coordinate of the active touch point
866     * @param y Y coordinate of the active touch point
867     * @return true if child views of v can be scrolled by delta of dx.
868     */
869    protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) {
870        if (v instanceof ViewGroup) {
871            final ViewGroup group = (ViewGroup) v;
872            final int scrollX = v.getScrollX();
873            final int scrollY = v.getScrollY();
874            final int count = group.getChildCount();
875            // Count backwards - let topmost views consume scroll distance first.
876            for (int i = count - 1; i >= 0; i--) {
877                // TODO: Add versioned support here for transformed views.
878                // This will not work for transformed views in Honeycomb+
879                final View child = group.getChildAt(i);
880                if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
881                        y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
882                        canScroll(child, true, dx, dy, x + scrollX - child.getLeft(),
883                                y + scrollY - child.getTop())) {
884                    return true;
885                }
886            }
887        }
888
889        return checkV && (ViewCompat.canScrollHorizontally(v, -dx) ||
890                ViewCompat.canScrollVertically(v, -dy));
891    }
892
893    /**
894     * Check if this event as provided to the parent view's onInterceptTouchEvent should
895     * cause the parent to intercept the touch event stream.
896     *
897     * @param ev MotionEvent provided to onInterceptTouchEvent
898     * @return true if the parent view should return true from onInterceptTouchEvent
899     */
900    public boolean shouldInterceptTouchEvent(MotionEvent ev) {
901        final int action = MotionEventCompat.getActionMasked(ev);
902        final int actionIndex = MotionEventCompat.getActionIndex(ev);
903
904        if (action == MotionEvent.ACTION_DOWN) {
905            // Reset things for a new event stream, just in case we didn't get
906            // the whole previous stream.
907            cancel();
908        }
909
910        if (mVelocityTracker == null) {
911            mVelocityTracker = VelocityTracker.obtain();
912        }
913        mVelocityTracker.addMovement(ev);
914
915        switch (action) {
916            case MotionEvent.ACTION_DOWN: {
917                final float x = ev.getX();
918                final float y = ev.getY();
919                final int pointerId = MotionEventCompat.getPointerId(ev, 0);
920                saveInitialMotion(x, y, pointerId);
921
922                final View toCapture = findTopChildUnder((int) x, (int) y);
923
924                // Catch a settling view if possible.
925                if (toCapture == mCapturedView && mDragState == STATE_SETTLING) {
926                    tryCaptureViewForDrag(toCapture, pointerId);
927                }
928
929                final int edgesTouched = mInitialEdgesTouched[pointerId];
930                if ((edgesTouched & mTrackingEdges) != 0) {
931                    mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
932                }
933                break;
934            }
935
936            case MotionEventCompat.ACTION_POINTER_DOWN: {
937                final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
938                final float x = MotionEventCompat.getX(ev, actionIndex);
939                final float y = MotionEventCompat.getY(ev, actionIndex);
940
941                saveInitialMotion(x, y, pointerId);
942
943                // A ViewDragHelper can only manipulate one view at a time.
944                if (mDragState == STATE_IDLE) {
945                    final int edgesTouched = mInitialEdgesTouched[pointerId];
946                    if ((edgesTouched & mTrackingEdges) != 0) {
947                        mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
948                    }
949                } else if (mDragState == STATE_SETTLING) {
950                    // Catch a settling view if possible.
951                    final View toCapture = findTopChildUnder((int) x, (int) y);
952                    if (toCapture == mCapturedView) {
953                        tryCaptureViewForDrag(toCapture, pointerId);
954                    }
955                }
956                break;
957            }
958
959            case MotionEvent.ACTION_MOVE: {
960                // First to cross a touch slop over a draggable view wins. Also report edge drags.
961                final int pointerCount = MotionEventCompat.getPointerCount(ev);
962                for (int i = 0; i < pointerCount; i++) {
963                    final int pointerId = MotionEventCompat.getPointerId(ev, i);
964                    final float x = MotionEventCompat.getX(ev, i);
965                    final float y = MotionEventCompat.getY(ev, i);
966                    final float dx = x - mInitialMotionX[pointerId];
967                    final float dy = y - mInitialMotionY[pointerId];
968
969                    reportNewEdgeDrags(dx, dy, pointerId);
970                    if (mDragState == STATE_DRAGGING) {
971                        // Callback might have started an edge drag
972                        break;
973                    }
974
975                    final View toCapture = findTopChildUnder((int) x, (int) y);
976                    if (toCapture != null && checkTouchSlop(toCapture, dx, dy) &&
977                            tryCaptureViewForDrag(toCapture, pointerId)) {
978                        break;
979                    }
980                }
981                saveLastMotion(ev);
982                break;
983            }
984
985            case MotionEventCompat.ACTION_POINTER_UP: {
986                final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
987                clearMotionHistory(pointerId);
988                break;
989            }
990
991            case MotionEvent.ACTION_UP:
992            case MotionEvent.ACTION_CANCEL: {
993                cancel();
994                break;
995            }
996        }
997
998        return mDragState == STATE_DRAGGING;
999    }
1000
1001    /**
1002     * Process a touch event received by the parent view. This method will dispatch callback events
1003     * as needed before returning. The parent view's onTouchEvent implementation should call this.
1004     *
1005     * @param ev The touch event received by the parent view
1006     */
1007    public void processTouchEvent(MotionEvent ev) {
1008        final int action = MotionEventCompat.getActionMasked(ev);
1009        final int actionIndex = MotionEventCompat.getActionIndex(ev);
1010
1011        if (action == MotionEvent.ACTION_DOWN) {
1012            // Reset things for a new event stream, just in case we didn't get
1013            // the whole previous stream.
1014            cancel();
1015        }
1016
1017        if (mVelocityTracker == null) {
1018            mVelocityTracker = VelocityTracker.obtain();
1019        }
1020        mVelocityTracker.addMovement(ev);
1021
1022        switch (action) {
1023            case MotionEvent.ACTION_DOWN: {
1024                final float x = ev.getX();
1025                final float y = ev.getY();
1026                final int pointerId = MotionEventCompat.getPointerId(ev, 0);
1027                final View toCapture = findTopChildUnder((int) x, (int) y);
1028
1029                saveInitialMotion(x, y, pointerId);
1030
1031                // Since the parent is already directly processing this touch event,
1032                // there is no reason to delay for a slop before dragging.
1033                // Start immediately if possible.
1034                tryCaptureViewForDrag(toCapture, pointerId);
1035
1036                final int edgesTouched = mInitialEdgesTouched[pointerId];
1037                if ((edgesTouched & mTrackingEdges) != 0) {
1038                    mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
1039                }
1040                break;
1041            }
1042
1043            case MotionEventCompat.ACTION_POINTER_DOWN: {
1044                final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
1045                final float x = MotionEventCompat.getX(ev, actionIndex);
1046                final float y = MotionEventCompat.getY(ev, actionIndex);
1047
1048                saveInitialMotion(x, y, pointerId);
1049
1050                // A ViewDragHelper can only manipulate one view at a time.
1051                if (mDragState == STATE_IDLE) {
1052                    // If we're idle we can do anything! Treat it like a normal down event.
1053
1054                    final View toCapture = findTopChildUnder((int) x, (int) y);
1055                    tryCaptureViewForDrag(toCapture, pointerId);
1056
1057                    final int edgesTouched = mInitialEdgesTouched[pointerId];
1058                    if ((edgesTouched & mTrackingEdges) != 0) {
1059                        mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
1060                    }
1061                } else if (isCapturedViewUnder((int) x, (int) y)) {
1062                    // We're still tracking a captured view. If the same view is under this
1063                    // point, we'll swap to controlling it with this pointer instead.
1064                    // (This will still work if we're "catching" a settling view.)
1065
1066                    tryCaptureViewForDrag(mCapturedView, pointerId);
1067                }
1068                break;
1069            }
1070
1071            case MotionEvent.ACTION_MOVE: {
1072                if (mDragState == STATE_DRAGGING) {
1073                    final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
1074                    final float x = MotionEventCompat.getX(ev, index);
1075                    final float y = MotionEventCompat.getY(ev, index);
1076                    final int idx = (int) (x - mLastMotionX[mActivePointerId]);
1077                    final int idy = (int) (y - mLastMotionY[mActivePointerId]);
1078
1079                    dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy);
1080
1081                    saveLastMotion(ev);
1082                } else {
1083                    // Check to see if any pointer is now over a draggable view.
1084                    final int pointerCount = MotionEventCompat.getPointerCount(ev);
1085                    for (int i = 0; i < pointerCount; i++) {
1086                        final int pointerId = MotionEventCompat.getPointerId(ev, i);
1087                        final float x = MotionEventCompat.getX(ev, i);
1088                        final float y = MotionEventCompat.getY(ev, i);
1089                        final float dx = x - mInitialMotionX[pointerId];
1090                        final float dy = y - mInitialMotionY[pointerId];
1091
1092                        reportNewEdgeDrags(dx, dy, pointerId);
1093                        if (mDragState == STATE_DRAGGING) {
1094                            // Callback might have started an edge drag.
1095                            break;
1096                        }
1097
1098                        final View toCapture = findTopChildUnder((int) x, (int) y);
1099                        if (checkTouchSlop(toCapture, dx, dy) &&
1100                                tryCaptureViewForDrag(toCapture, pointerId)) {
1101                            break;
1102                        }
1103                    }
1104                    saveLastMotion(ev);
1105                }
1106                break;
1107            }
1108
1109            case MotionEventCompat.ACTION_POINTER_UP: {
1110                final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
1111                if (mDragState == STATE_DRAGGING && pointerId == mActivePointerId) {
1112                    // Try to find another pointer that's still holding on to the captured view.
1113                    int newActivePointer = INVALID_POINTER;
1114                    final int pointerCount = MotionEventCompat.getPointerCount(ev);
1115                    for (int i = 0; i < pointerCount; i++) {
1116                        final int id = MotionEventCompat.getPointerId(ev, i);
1117                        if (id == mActivePointerId) {
1118                            // This one's going away, skip.
1119                            continue;
1120                        }
1121
1122                        final float x = MotionEventCompat.getX(ev, i);
1123                        final float y = MotionEventCompat.getY(ev, i);
1124                        if (findTopChildUnder((int) x, (int) y) == mCapturedView &&
1125                                tryCaptureViewForDrag(mCapturedView, id)) {
1126                            newActivePointer = mActivePointerId;
1127                            break;
1128                        }
1129                    }
1130
1131                    if (newActivePointer == INVALID_POINTER) {
1132                        // We didn't find another pointer still touching the view, release it.
1133                        releaseViewForPointerUp();
1134                    }
1135                }
1136                clearMotionHistory(pointerId);
1137                break;
1138            }
1139
1140            case MotionEvent.ACTION_UP: {
1141                if (mDragState == STATE_DRAGGING) {
1142                    releaseViewForPointerUp();
1143                }
1144                cancel();
1145                break;
1146            }
1147
1148            case MotionEvent.ACTION_CANCEL: {
1149                if (mDragState == STATE_DRAGGING) {
1150                    dispatchViewReleased(0, 0);
1151                }
1152                cancel();
1153                break;
1154            }
1155        }
1156    }
1157
1158    private void reportNewEdgeDrags(float dx, float dy, int pointerId) {
1159        int dragsStarted = 0;
1160        if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) {
1161            dragsStarted |= EDGE_LEFT;
1162        }
1163        if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) {
1164            dragsStarted |= EDGE_TOP;
1165        }
1166        if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) {
1167            dragsStarted |= EDGE_RIGHT;
1168        }
1169        if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) {
1170            dragsStarted |= EDGE_BOTTOM;
1171        }
1172
1173        if (dragsStarted != 0) {
1174            mEdgeDragsInProgress[pointerId] |= dragsStarted;
1175            mCallback.onEdgeDragStarted(dragsStarted, pointerId);
1176        }
1177    }
1178
1179    private boolean checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge) {
1180        final float absDelta = Math.abs(delta);
1181        final float absODelta = Math.abs(odelta);
1182
1183        if ((mInitialEdgesTouched[pointerId] & edge) != edge  || (mTrackingEdges & edge) == 0 ||
1184                (mEdgeDragsLocked[pointerId] & edge) == edge ||
1185                (mEdgeDragsInProgress[pointerId] & edge) == edge ||
1186                (absDelta <= mTouchSlop && absODelta <= mTouchSlop)) {
1187            return false;
1188        }
1189        if (absDelta < absODelta * 0.5f && mCallback.onEdgeLock(edge)) {
1190            mEdgeDragsLocked[pointerId] |= edge;
1191            return false;
1192        }
1193        return (mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > mTouchSlop;
1194    }
1195
1196    /**
1197     * Check if we've crossed a reasonable touch slop for the given child view.
1198     * If the child cannot be dragged along the horizontal or vertical axis, motion
1199     * along that axis will not count toward the slop check.
1200     *
1201     * @param child Child to check
1202     * @param dx Motion since initial position along X axis
1203     * @param dy Motion since initial position along Y axis
1204     * @return true if the touch slop has been crossed
1205     */
1206    private boolean checkTouchSlop(View child, float dx, float dy) {
1207        if (child == null) {
1208            return false;
1209        }
1210        final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0;
1211        final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0;
1212
1213        if (checkHorizontal && checkVertical) {
1214            return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
1215        } else if (checkHorizontal) {
1216            return Math.abs(dx) > mTouchSlop;
1217        } else if (checkVertical) {
1218            return Math.abs(dy) > mTouchSlop;
1219        }
1220        return false;
1221    }
1222
1223    /**
1224     * Check if any pointer tracked in the current gesture has crossed
1225     * the required slop threshold.
1226     *
1227     * <p>This depends on internal state populated by
1228     * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
1229     * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on
1230     * the results of this method after all currently available touch data
1231     * has been provided to one of these two methods.</p>
1232     *
1233     * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL},
1234     *                   {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL}
1235     * @return true if the slop threshold has been crossed, false otherwise
1236     */
1237    public boolean checkTouchSlop(int directions) {
1238        final int count = mInitialMotionX.length;
1239        for (int i = 0; i < count; i++) {
1240            if (checkTouchSlop(directions, i)) {
1241                return true;
1242            }
1243        }
1244        return false;
1245    }
1246
1247    /**
1248     * Check if the specified pointer tracked in the current gesture has crossed
1249     * the required slop threshold.
1250     *
1251     * <p>This depends on internal state populated by
1252     * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
1253     * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on
1254     * the results of this method after all currently available touch data
1255     * has been provided to one of these two methods.</p>
1256     *
1257     * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL},
1258     *                   {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL}
1259     * @param pointerId ID of the pointer to slop check as specified by MotionEvent
1260     * @return true if the slop threshold has been crossed, false otherwise
1261     */
1262    public boolean checkTouchSlop(int directions, int pointerId) {
1263        if (!isPointerDown(pointerId)) {
1264            return false;
1265        }
1266
1267        final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL;
1268        final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL;
1269
1270        final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId];
1271        final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId];
1272
1273        if (checkHorizontal && checkVertical) {
1274            return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
1275        } else if (checkHorizontal) {
1276            return Math.abs(dx) > mTouchSlop;
1277        } else if (checkVertical) {
1278            return Math.abs(dy) > mTouchSlop;
1279        }
1280        return false;
1281    }
1282
1283    /**
1284     * Check if any of the edges specified were initially touched in the currently active gesture.
1285     * If there is no currently active gesture this method will return false.
1286     *
1287     * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT},
1288     *              {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and
1289     *              {@link #EDGE_ALL}
1290     * @return true if any of the edges specified were initially touched in the current gesture
1291     */
1292    public boolean isEdgeTouched(int edges) {
1293        final int count = mInitialEdgesTouched.length;
1294        for (int i = 0; i < count; i++) {
1295            if (isEdgeTouched(edges, i)) {
1296                return true;
1297            }
1298        }
1299        return false;
1300    }
1301
1302    /**
1303     * Check if any of the edges specified were initially touched by the pointer with
1304     * the specified ID. If there is no currently active gesture or if there is no pointer with
1305     * the given ID currently down this method will return false.
1306     *
1307     * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT},
1308     *              {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and
1309     *              {@link #EDGE_ALL}
1310     * @return true if any of the edges specified were initially touched in the current gesture
1311     */
1312    public boolean isEdgeTouched(int edges, int pointerId) {
1313        return isPointerDown(pointerId) && (mInitialEdgesTouched[pointerId] & edges) != 0;
1314    }
1315
1316    private void releaseViewForPointerUp() {
1317        mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
1318        dispatchViewReleased(VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
1319                VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId));
1320    }
1321
1322    private void dragTo(int left, int top, int dx, int dy) {
1323        int clampedX = left;
1324        int clampedY = top;
1325        final int oldLeft = mCapturedView.getLeft();
1326        final int oldTop = mCapturedView.getTop();
1327        if (dx != 0) {
1328            clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
1329            mCapturedView.offsetLeftAndRight(clampedX - oldLeft);
1330        }
1331        if (dy != 0) {
1332            clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
1333            mCapturedView.offsetTopAndBottom(clampedY - oldTop);
1334        }
1335
1336        if (dx != 0 || dy != 0) {
1337            final int clampedDx = clampedX - oldLeft;
1338            final int clampedDy = clampedY - oldTop;
1339            mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY,
1340                    clampedDx, clampedDy);
1341        }
1342    }
1343
1344    /**
1345     * Determine if the currently captured view is under the given point in the
1346     * parent view's coordinate system. If there is no captured view this method
1347     * will return false.
1348     *
1349     * @param x X position to test in the parent's coordinate system
1350     * @param y Y position to test in the parent's coordinate system
1351     * @return true if the captured view is under the given point, false otherwise
1352     */
1353    public boolean isCapturedViewUnder(int x, int y) {
1354        return isViewUnder(mCapturedView, x, y);
1355    }
1356
1357    /**
1358     * Determine if the supplied view is under the given point in the
1359     * parent view's coordinate system.
1360     *
1361     * @param view Child view of the parent to hit test
1362     * @param x X position to test in the parent's coordinate system
1363     * @param y Y position to test in the parent's coordinate system
1364     * @return true if the supplied view is under the given point, false otherwise
1365     */
1366    public boolean isViewUnder(View view, int x, int y) {
1367        if (view == null) {
1368            return false;
1369        }
1370        return x >= view.getLeft() &&
1371                x < view.getRight() &&
1372                y >= view.getTop() &&
1373                y < view.getBottom();
1374    }
1375
1376    /**
1377     * Find the topmost child under the given point within the parent view's coordinate system.
1378     * The child order is determined using {@link Callback#getOrderedChildIndex(int)}.
1379     *
1380     * @param x X position to test in the parent's coordinate system
1381     * @param y Y position to test in the parent's coordinate system
1382     * @return The topmost child view under (x, y) or null if none found.
1383     */
1384    public View findTopChildUnder(int x, int y) {
1385        final int childCount = mParentView.getChildCount();
1386        for (int i = childCount - 1; i >= 0; i--) {
1387            final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
1388            if (x >= child.getLeft() && x < child.getRight() &&
1389                    y >= child.getTop() && y < child.getBottom()) {
1390                return child;
1391            }
1392        }
1393        return null;
1394    }
1395
1396    private int getEdgesTouched(int x, int y) {
1397        int result = 0;
1398
1399        if (x < mParentView.getLeft() + mEdgeSize) result |= EDGE_LEFT;
1400        if (y < mParentView.getTop() + mEdgeSize) result |= EDGE_TOP;
1401        if (x > mParentView.getRight() - mEdgeSize) result |= EDGE_RIGHT;
1402        if (y > mParentView.getBottom() - mEdgeSize) result |= EDGE_BOTTOM;
1403
1404        return result;
1405    }
1406}
1407