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 
18 package android.support.v4.widget;
19 
20 import android.content.Context;
21 import android.support.v4.view.MotionEventCompat;
22 import android.support.v4.view.VelocityTrackerCompat;
23 import android.support.v4.view.ViewCompat;
24 import android.view.MotionEvent;
25 import android.view.VelocityTracker;
26 import android.view.View;
27 import android.view.ViewConfiguration;
28 import android.view.ViewGroup;
29 import android.view.animation.Interpolator;
30 
31 import 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  */
38 public 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 = 20; // 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          */
onViewDragStateChanged(int state)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          */
onViewPositionChanged(View changedView, int left, int top, int dx, int dy)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          */
onViewCaptured(View capturedChild, int activePointerId)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          */
onViewReleased(View releasedChild, float xvel, float yvel)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          */
onEdgeTouched(int edgeFlags, int pointerId)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          */
onEdgeLock(int edgeFlags)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          */
onEdgeDragStarted(int edgeFlags, int pointerId)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          */
getOrderedChildIndex(int index)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          */
getViewHorizontalDragRange(View child)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          */
getViewVerticalDragRange(View child)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          */
tryCaptureView(View child, int pointerId)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          */
clampViewPositionHorizontal(View child, int left, int dx)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          */
clampViewPositionVertical(View child, int top, int dy)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      */
create(ViewGroup forParent, Callback cb)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      */
create(ViewGroup forParent, float sensitivity, Callback cb)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      */
ViewDragHelper(Context context, ViewGroup forParent, Callback cb)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      * Set the minimum velocity that will be detected as having a magnitude greater than zero
396      * in pixels per second. Callback methods accepting a velocity will be clamped appropriately.
397      *
398      * @param minVel Minimum velocity to detect
399      */
setMinVelocity(float minVel)400     public void setMinVelocity(float minVel) {
401         mMinVelocity = minVel;
402     }
403 
404     /**
405      * Return the currently configured minimum velocity. Any flings with a magnitude less
406      * than this value in pixels per second. Callback methods accepting a velocity will receive
407      * zero as a velocity value if the real detected velocity was below this threshold.
408      *
409      * @return the minimum velocity that will be detected
410      */
getMinVelocity()411     public float getMinVelocity() {
412         return mMinVelocity;
413     }
414 
415     /**
416      * Retrieve the current drag state of this helper. This will return one of
417      * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
418      * @return The current drag state
419      */
getViewDragState()420     public int getViewDragState() {
421         return mDragState;
422     }
423 
424     /**
425      * Enable edge tracking for the selected edges of the parent view.
426      * The callback's {@link Callback#onEdgeTouched(int, int)} and
427      * {@link Callback#onEdgeDragStarted(int, int)} methods will only be invoked
428      * for edges for which edge tracking has been enabled.
429      *
430      * @param edgeFlags Combination of edge flags describing the edges to watch
431      * @see #EDGE_LEFT
432      * @see #EDGE_TOP
433      * @see #EDGE_RIGHT
434      * @see #EDGE_BOTTOM
435      */
setEdgeTrackingEnabled(int edgeFlags)436     public void setEdgeTrackingEnabled(int edgeFlags) {
437         mTrackingEdges = edgeFlags;
438     }
439 
440     /**
441      * Return the size of an edge. This is the range in pixels along the edges of this view
442      * that will actively detect edge touches or drags if edge tracking is enabled.
443      *
444      * @return The size of an edge in pixels
445      * @see #setEdgeTrackingEnabled(int)
446      */
getEdgeSize()447     public int getEdgeSize() {
448         return mEdgeSize;
449     }
450 
451     /**
452      * Capture a specific child view for dragging within the parent. The callback will be notified
453      * but {@link Callback#tryCaptureView(android.view.View, int)} will not be asked permission to
454      * capture this view.
455      *
456      * @param childView Child view to capture
457      * @param activePointerId ID of the pointer that is dragging the captured child view
458      */
captureChildView(View childView, int activePointerId)459     public void captureChildView(View childView, int activePointerId) {
460         if (childView.getParent() != mParentView) {
461             throw new IllegalArgumentException("captureChildView: parameter must be a descendant " +
462                     "of the ViewDragHelper's tracked parent view (" + mParentView + ")");
463         }
464 
465         mCapturedView = childView;
466         mActivePointerId = activePointerId;
467         mCallback.onViewCaptured(childView, activePointerId);
468         setDragState(STATE_DRAGGING);
469     }
470 
471     /**
472      * @return The currently captured view, or null if no view has been captured.
473      */
getCapturedView()474     public View getCapturedView() {
475         return mCapturedView;
476     }
477 
478     /**
479      * @return The ID of the pointer currently dragging the captured view,
480      *         or {@link #INVALID_POINTER}.
481      */
getActivePointerId()482     public int getActivePointerId() {
483         return mActivePointerId;
484     }
485 
486     /**
487      * @return The minimum distance in pixels that the user must travel to initiate a drag
488      */
getTouchSlop()489     public int getTouchSlop() {
490         return mTouchSlop;
491     }
492 
493     /**
494      * The result of a call to this method is equivalent to
495      * {@link #processTouchEvent(android.view.MotionEvent)} receiving an ACTION_CANCEL event.
496      */
cancel()497     public void cancel() {
498         mActivePointerId = INVALID_POINTER;
499         clearMotionHistory();
500 
501         if (mVelocityTracker != null) {
502             mVelocityTracker.recycle();
503             mVelocityTracker = null;
504         }
505     }
506 
507     /**
508      * {@link #cancel()}, but also abort all motion in progress and snap to the end of any
509      * animation.
510      */
abort()511     public void abort() {
512         cancel();
513         if (mDragState == STATE_SETTLING) {
514             final int oldX = mScroller.getCurrX();
515             final int oldY = mScroller.getCurrY();
516             mScroller.abortAnimation();
517             final int newX = mScroller.getCurrX();
518             final int newY = mScroller.getCurrY();
519             mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY);
520         }
521         setDragState(STATE_IDLE);
522     }
523 
524     /**
525      * Animate the view <code>child</code> to the given (left, top) position.
526      * If this method returns true, the caller should invoke {@link #continueSettling(boolean)}
527      * on each subsequent frame to continue the motion until it returns false. If this method
528      * returns false there is no further work to do to complete the movement.
529      *
530      * <p>This operation does not count as a capture event, though {@link #getCapturedView()}
531      * will still report the sliding view while the slide is in progress.</p>
532      *
533      * @param child Child view to capture and animate
534      * @param finalLeft Final left position of child
535      * @param finalTop Final top position of child
536      * @return true if animation should continue through {@link #continueSettling(boolean)} calls
537      */
smoothSlideViewTo(View child, int finalLeft, int finalTop)538     public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) {
539         mCapturedView = child;
540         mActivePointerId = INVALID_POINTER;
541 
542         boolean continueSliding = forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0);
543         if (!continueSliding && mDragState == STATE_IDLE && mCapturedView != null) {
544             // If we're in an IDLE state to begin with and aren't moving anywhere, we
545             // end up having a non-null capturedView with an IDLE dragState
546             mCapturedView = null;
547         }
548 
549         return continueSliding;
550     }
551 
552     /**
553      * Settle the captured view at the given (left, top) position.
554      * The appropriate velocity from prior motion will be taken into account.
555      * If this method returns true, the caller should invoke {@link #continueSettling(boolean)}
556      * on each subsequent frame to continue the motion until it returns false. If this method
557      * returns false there is no further work to do to complete the movement.
558      *
559      * @param finalLeft Settled left edge position for the captured view
560      * @param finalTop Settled top edge position for the captured view
561      * @return true if animation should continue through {@link #continueSettling(boolean)} calls
562      */
settleCapturedViewAt(int finalLeft, int finalTop)563     public boolean settleCapturedViewAt(int finalLeft, int finalTop) {
564         if (!mReleaseInProgress) {
565             throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to " +
566                     "Callback#onViewReleased");
567         }
568 
569         return forceSettleCapturedViewAt(finalLeft, finalTop,
570                 (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
571                 (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId));
572     }
573 
574     /**
575      * Settle the captured view at the given (left, top) position.
576      *
577      * @param finalLeft Target left position for the captured view
578      * @param finalTop Target top position for the captured view
579      * @param xvel Horizontal velocity
580      * @param yvel Vertical velocity
581      * @return true if animation should continue through {@link #continueSettling(boolean)} calls
582      */
forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel)583     private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) {
584         final int startLeft = mCapturedView.getLeft();
585         final int startTop = mCapturedView.getTop();
586         final int dx = finalLeft - startLeft;
587         final int dy = finalTop - startTop;
588 
589         if (dx == 0 && dy == 0) {
590             // Nothing to do. Send callbacks, be done.
591             mScroller.abortAnimation();
592             setDragState(STATE_IDLE);
593             return false;
594         }
595 
596         final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel);
597         mScroller.startScroll(startLeft, startTop, dx, dy, duration);
598 
599         setDragState(STATE_SETTLING);
600         return true;
601     }
602 
computeSettleDuration(View child, int dx, int dy, int xvel, int yvel)603     private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) {
604         xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity);
605         yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity);
606         final int absDx = Math.abs(dx);
607         final int absDy = Math.abs(dy);
608         final int absXVel = Math.abs(xvel);
609         final int absYVel = Math.abs(yvel);
610         final int addedVel = absXVel + absYVel;
611         final int addedDistance = absDx + absDy;
612 
613         final float xweight = xvel != 0 ? (float) absXVel / addedVel :
614                 (float) absDx / addedDistance;
615         final float yweight = yvel != 0 ? (float) absYVel / addedVel :
616                 (float) absDy / addedDistance;
617 
618         int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child));
619         int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child));
620 
621         return (int) (xduration * xweight + yduration * yweight);
622     }
623 
computeAxisDuration(int delta, int velocity, int motionRange)624     private int computeAxisDuration(int delta, int velocity, int motionRange) {
625         if (delta == 0) {
626             return 0;
627         }
628 
629         final int width = mParentView.getWidth();
630         final int halfWidth = width / 2;
631         final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width);
632         final float distance = halfWidth + halfWidth *
633                 distanceInfluenceForSnapDuration(distanceRatio);
634 
635         int duration;
636         velocity = Math.abs(velocity);
637         if (velocity > 0) {
638             duration = 4 * Math.round(1000 * Math.abs(distance / velocity));
639         } else {
640             final float range = (float) Math.abs(delta) / motionRange;
641             duration = (int) ((range + 1) * BASE_SETTLE_DURATION);
642         }
643         return Math.min(duration, MAX_SETTLE_DURATION);
644     }
645 
646     /**
647      * Clamp the magnitude of value for absMin and absMax.
648      * If the value is below the minimum, it will be clamped to zero.
649      * If the value is above the maximum, it will be clamped to the maximum.
650      *
651      * @param value Value to clamp
652      * @param absMin Absolute value of the minimum significant value to return
653      * @param absMax Absolute value of the maximum value to return
654      * @return The clamped value with the same sign as <code>value</code>
655      */
clampMag(int value, int absMin, int absMax)656     private int clampMag(int value, int absMin, int absMax) {
657         final int absValue = Math.abs(value);
658         if (absValue < absMin) return 0;
659         if (absValue > absMax) return value > 0 ? absMax : -absMax;
660         return value;
661     }
662 
663     /**
664      * Clamp the magnitude of value for absMin and absMax.
665      * If the value is below the minimum, it will be clamped to zero.
666      * If the value is above the maximum, it will be clamped to the maximum.
667      *
668      * @param value Value to clamp
669      * @param absMin Absolute value of the minimum significant value to return
670      * @param absMax Absolute value of the maximum value to return
671      * @return The clamped value with the same sign as <code>value</code>
672      */
clampMag(float value, float absMin, float absMax)673     private float clampMag(float value, float absMin, float absMax) {
674         final float absValue = Math.abs(value);
675         if (absValue < absMin) return 0;
676         if (absValue > absMax) return value > 0 ? absMax : -absMax;
677         return value;
678     }
679 
distanceInfluenceForSnapDuration(float f)680     private float distanceInfluenceForSnapDuration(float f) {
681         f -= 0.5f; // center the values about 0.
682         f *= 0.3f * Math.PI / 2.0f;
683         return (float) Math.sin(f);
684     }
685 
686     /**
687      * Settle the captured view based on standard free-moving fling behavior.
688      * The caller should invoke {@link #continueSettling(boolean)} on each subsequent frame
689      * to continue the motion until it returns false.
690      *
691      * @param minLeft Minimum X position for the view's left edge
692      * @param minTop Minimum Y position for the view's top edge
693      * @param maxLeft Maximum X position for the view's left edge
694      * @param maxTop Maximum Y position for the view's top edge
695      */
flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop)696     public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {
697         if (!mReleaseInProgress) {
698             throw new IllegalStateException("Cannot flingCapturedView outside of a call to " +
699                     "Callback#onViewReleased");
700         }
701 
702         mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(),
703                 (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
704                 (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
705                 minLeft, maxLeft, minTop, maxTop);
706 
707         setDragState(STATE_SETTLING);
708     }
709 
710     /**
711      * Move the captured settling view by the appropriate amount for the current time.
712      * If <code>continueSettling</code> returns true, the caller should call it again
713      * on the next frame to continue.
714      *
715      * @param deferCallbacks true if state callbacks should be deferred via posted message.
716      *                       Set this to true if you are calling this method from
717      *                       {@link android.view.View#computeScroll()} or similar methods
718      *                       invoked as part of layout or drawing.
719      * @return true if settle is still in progress
720      */
continueSettling(boolean deferCallbacks)721     public boolean continueSettling(boolean deferCallbacks) {
722         if (mDragState == STATE_SETTLING) {
723             boolean keepGoing = mScroller.computeScrollOffset();
724             final int x = mScroller.getCurrX();
725             final int y = mScroller.getCurrY();
726             final int dx = x - mCapturedView.getLeft();
727             final int dy = y - mCapturedView.getTop();
728 
729             if (dx != 0) {
730                 mCapturedView.offsetLeftAndRight(dx);
731             }
732             if (dy != 0) {
733                 mCapturedView.offsetTopAndBottom(dy);
734             }
735 
736             if (dx != 0 || dy != 0) {
737                 mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
738             }
739 
740             if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
741                 // Close enough. The interpolator/scroller might think we're still moving
742                 // but the user sure doesn't.
743                 mScroller.abortAnimation();
744                 keepGoing = false;
745             }
746 
747             if (!keepGoing) {
748                 if (deferCallbacks) {
749                     mParentView.post(mSetIdleRunnable);
750                 } else {
751                     setDragState(STATE_IDLE);
752                 }
753             }
754         }
755 
756         return mDragState == STATE_SETTLING;
757     }
758 
759     /**
760      * Like all callback events this must happen on the UI thread, but release
761      * involves some extra semantics. During a release (mReleaseInProgress)
762      * is the only time it is valid to call {@link #settleCapturedViewAt(int, int)}
763      * or {@link #flingCapturedView(int, int, int, int)}.
764      */
dispatchViewReleased(float xvel, float yvel)765     private void dispatchViewReleased(float xvel, float yvel) {
766         mReleaseInProgress = true;
767         mCallback.onViewReleased(mCapturedView, xvel, yvel);
768         mReleaseInProgress = false;
769 
770         if (mDragState == STATE_DRAGGING) {
771             // onViewReleased didn't call a method that would have changed this. Go idle.
772             setDragState(STATE_IDLE);
773         }
774     }
775 
clearMotionHistory()776     private void clearMotionHistory() {
777         if (mInitialMotionX == null) {
778             return;
779         }
780         Arrays.fill(mInitialMotionX, 0);
781         Arrays.fill(mInitialMotionY, 0);
782         Arrays.fill(mLastMotionX, 0);
783         Arrays.fill(mLastMotionY, 0);
784         Arrays.fill(mInitialEdgesTouched, 0);
785         Arrays.fill(mEdgeDragsInProgress, 0);
786         Arrays.fill(mEdgeDragsLocked, 0);
787         mPointersDown = 0;
788     }
789 
clearMotionHistory(int pointerId)790     private void clearMotionHistory(int pointerId) {
791         if (mInitialMotionX == null) {
792             return;
793         }
794         mInitialMotionX[pointerId] = 0;
795         mInitialMotionY[pointerId] = 0;
796         mLastMotionX[pointerId] = 0;
797         mLastMotionY[pointerId] = 0;
798         mInitialEdgesTouched[pointerId] = 0;
799         mEdgeDragsInProgress[pointerId] = 0;
800         mEdgeDragsLocked[pointerId] = 0;
801         mPointersDown &= ~(1 << pointerId);
802     }
803 
ensureMotionHistorySizeForId(int pointerId)804     private void ensureMotionHistorySizeForId(int pointerId) {
805         if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) {
806             float[] imx = new float[pointerId + 1];
807             float[] imy = new float[pointerId + 1];
808             float[] lmx = new float[pointerId + 1];
809             float[] lmy = new float[pointerId + 1];
810             int[] iit = new int[pointerId + 1];
811             int[] edip = new int[pointerId + 1];
812             int[] edl = new int[pointerId + 1];
813 
814             if (mInitialMotionX != null) {
815                 System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length);
816                 System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length);
817                 System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length);
818                 System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length);
819                 System.arraycopy(mInitialEdgesTouched, 0, iit, 0, mInitialEdgesTouched.length);
820                 System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length);
821                 System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length);
822             }
823 
824             mInitialMotionX = imx;
825             mInitialMotionY = imy;
826             mLastMotionX = lmx;
827             mLastMotionY = lmy;
828             mInitialEdgesTouched = iit;
829             mEdgeDragsInProgress = edip;
830             mEdgeDragsLocked = edl;
831         }
832     }
833 
saveInitialMotion(float x, float y, int pointerId)834     private void saveInitialMotion(float x, float y, int pointerId) {
835         ensureMotionHistorySizeForId(pointerId);
836         mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
837         mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
838         mInitialEdgesTouched[pointerId] = getEdgesTouched((int) x, (int) y);
839         mPointersDown |= 1 << pointerId;
840     }
841 
saveLastMotion(MotionEvent ev)842     private void saveLastMotion(MotionEvent ev) {
843         final int pointerCount = MotionEventCompat.getPointerCount(ev);
844         for (int i = 0; i < pointerCount; i++) {
845             final int pointerId = MotionEventCompat.getPointerId(ev, i);
846             final float x = MotionEventCompat.getX(ev, i);
847             final float y = MotionEventCompat.getY(ev, i);
848             mLastMotionX[pointerId] = x;
849             mLastMotionY[pointerId] = y;
850         }
851     }
852 
853     /**
854      * Check if the given pointer ID represents a pointer that is currently down (to the best
855      * of the ViewDragHelper's knowledge).
856      *
857      * <p>The state used to report this information is populated by the methods
858      * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
859      * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these methods has not
860      * been called for all relevant MotionEvents to track, the information reported
861      * by this method may be stale or incorrect.</p>
862      *
863      * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent
864      * @return true if the pointer with the given ID is still down
865      */
isPointerDown(int pointerId)866     public boolean isPointerDown(int pointerId) {
867         return (mPointersDown & 1 << pointerId) != 0;
868     }
869 
setDragState(int state)870     void setDragState(int state) {
871         mParentView.removeCallbacks(mSetIdleRunnable);
872         if (mDragState != state) {
873             mDragState = state;
874             mCallback.onViewDragStateChanged(state);
875             if (mDragState == STATE_IDLE) {
876                 mCapturedView = null;
877             }
878         }
879     }
880 
881     /**
882      * Attempt to capture the view with the given pointer ID. The callback will be involved.
883      * This will put us into the "dragging" state. If we've already captured this view with
884      * this pointer this method will immediately return true without consulting the callback.
885      *
886      * @param toCapture View to capture
887      * @param pointerId Pointer to capture with
888      * @return true if capture was successful
889      */
tryCaptureViewForDrag(View toCapture, int pointerId)890     boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
891         if (toCapture == mCapturedView && mActivePointerId == pointerId) {
892             // Already done!
893             return true;
894         }
895         if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
896             mActivePointerId = pointerId;
897             captureChildView(toCapture, pointerId);
898             return true;
899         }
900         return false;
901     }
902 
903     /**
904      * Tests scrollability within child views of v given a delta of dx.
905      *
906      * @param v View to test for horizontal scrollability
907      * @param checkV Whether the view v passed should itself be checked for scrollability (true),
908      *               or just its children (false).
909      * @param dx Delta scrolled in pixels along the X axis
910      * @param dy Delta scrolled in pixels along the Y axis
911      * @param x X coordinate of the active touch point
912      * @param y Y coordinate of the active touch point
913      * @return true if child views of v can be scrolled by delta of dx.
914      */
canScroll(View v, boolean checkV, int dx, int dy, int x, int y)915     protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) {
916         if (v instanceof ViewGroup) {
917             final ViewGroup group = (ViewGroup) v;
918             final int scrollX = v.getScrollX();
919             final int scrollY = v.getScrollY();
920             final int count = group.getChildCount();
921             // Count backwards - let topmost views consume scroll distance first.
922             for (int i = count - 1; i >= 0; i--) {
923                 // TODO: Add versioned support here for transformed views.
924                 // This will not work for transformed views in Honeycomb+
925                 final View child = group.getChildAt(i);
926                 if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() &&
927                         y + scrollY >= child.getTop() && y + scrollY < child.getBottom() &&
928                         canScroll(child, true, dx, dy, x + scrollX - child.getLeft(),
929                                 y + scrollY - child.getTop())) {
930                     return true;
931                 }
932             }
933         }
934 
935         return checkV && (ViewCompat.canScrollHorizontally(v, -dx) ||
936                 ViewCompat.canScrollVertically(v, -dy));
937     }
938 
939     /**
940      * Check if this event as provided to the parent view's onInterceptTouchEvent should
941      * cause the parent to intercept the touch event stream.
942      *
943      * @param ev MotionEvent provided to onInterceptTouchEvent
944      * @return true if the parent view should return true from onInterceptTouchEvent
945      */
shouldInterceptTouchEvent(MotionEvent ev)946     public boolean shouldInterceptTouchEvent(MotionEvent ev) {
947         final int action = MotionEventCompat.getActionMasked(ev);
948         final int actionIndex = MotionEventCompat.getActionIndex(ev);
949 
950         if (action == MotionEvent.ACTION_DOWN) {
951             // Reset things for a new event stream, just in case we didn't get
952             // the whole previous stream.
953             cancel();
954         }
955 
956         if (mVelocityTracker == null) {
957             mVelocityTracker = VelocityTracker.obtain();
958         }
959         mVelocityTracker.addMovement(ev);
960 
961         switch (action) {
962             case MotionEvent.ACTION_DOWN: {
963                 final float x = ev.getX();
964                 final float y = ev.getY();
965                 final int pointerId = MotionEventCompat.getPointerId(ev, 0);
966                 saveInitialMotion(x, y, pointerId);
967 
968                 final View toCapture = findTopChildUnder((int) x, (int) y);
969 
970                 // Catch a settling view if possible.
971                 if (toCapture == mCapturedView && mDragState == STATE_SETTLING) {
972                     tryCaptureViewForDrag(toCapture, pointerId);
973                 }
974 
975                 final int edgesTouched = mInitialEdgesTouched[pointerId];
976                 if ((edgesTouched & mTrackingEdges) != 0) {
977                     mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
978                 }
979                 break;
980             }
981 
982             case MotionEventCompat.ACTION_POINTER_DOWN: {
983                 final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
984                 final float x = MotionEventCompat.getX(ev, actionIndex);
985                 final float y = MotionEventCompat.getY(ev, actionIndex);
986 
987                 saveInitialMotion(x, y, pointerId);
988 
989                 // A ViewDragHelper can only manipulate one view at a time.
990                 if (mDragState == STATE_IDLE) {
991                     final int edgesTouched = mInitialEdgesTouched[pointerId];
992                     if ((edgesTouched & mTrackingEdges) != 0) {
993                         mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
994                     }
995                 } else if (mDragState == STATE_SETTLING) {
996                     // Catch a settling view if possible.
997                     final View toCapture = findTopChildUnder((int) x, (int) y);
998                     if (toCapture == mCapturedView) {
999                         tryCaptureViewForDrag(toCapture, pointerId);
1000                     }
1001                 }
1002                 break;
1003             }
1004 
1005             case MotionEvent.ACTION_MOVE: {
1006                 if (mInitialMotionX == null || mInitialMotionY == null) break;
1007 
1008                 // First to cross a touch slop over a draggable view wins. Also report edge drags.
1009                 final int pointerCount = MotionEventCompat.getPointerCount(ev);
1010                 for (int i = 0; i < pointerCount; i++) {
1011                     final int pointerId = MotionEventCompat.getPointerId(ev, i);
1012                     final float x = MotionEventCompat.getX(ev, i);
1013                     final float y = MotionEventCompat.getY(ev, i);
1014                     final float dx = x - mInitialMotionX[pointerId];
1015                     final float dy = y - mInitialMotionY[pointerId];
1016 
1017                     final View toCapture = findTopChildUnder((int) x, (int) y);
1018                     final boolean pastSlop = toCapture != null && checkTouchSlop(toCapture, dx, dy);
1019                     if (pastSlop) {
1020                         // check the callback's
1021                         // getView[Horizontal|Vertical]DragRange methods to know
1022                         // if you can move at all along an axis, then see if it
1023                         // would clamp to the same value. If you can't move at
1024                         // all in every dimension with a nonzero range, bail.
1025                         final int oldLeft = toCapture.getLeft();
1026                         final int targetLeft = oldLeft + (int) dx;
1027                         final int newLeft = mCallback.clampViewPositionHorizontal(toCapture,
1028                                 targetLeft, (int) dx);
1029                         final int oldTop = toCapture.getTop();
1030                         final int targetTop = oldTop + (int) dy;
1031                         final int newTop = mCallback.clampViewPositionVertical(toCapture, targetTop,
1032                                 (int) dy);
1033                         final int horizontalDragRange = mCallback.getViewHorizontalDragRange(
1034                                 toCapture);
1035                         final int verticalDragRange = mCallback.getViewVerticalDragRange(toCapture);
1036                         if ((horizontalDragRange == 0 || horizontalDragRange > 0
1037                                 && newLeft == oldLeft) && (verticalDragRange == 0
1038                                 || verticalDragRange > 0 && newTop == oldTop)) {
1039                             break;
1040                         }
1041                     }
1042                     reportNewEdgeDrags(dx, dy, pointerId);
1043                     if (mDragState == STATE_DRAGGING) {
1044                         // Callback might have started an edge drag
1045                         break;
1046                     }
1047 
1048                     if (pastSlop && tryCaptureViewForDrag(toCapture, pointerId)) {
1049                         break;
1050                     }
1051                 }
1052                 saveLastMotion(ev);
1053                 break;
1054             }
1055 
1056             case MotionEventCompat.ACTION_POINTER_UP: {
1057                 final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
1058                 clearMotionHistory(pointerId);
1059                 break;
1060             }
1061 
1062             case MotionEvent.ACTION_UP:
1063             case MotionEvent.ACTION_CANCEL: {
1064                 cancel();
1065                 break;
1066             }
1067         }
1068 
1069         return mDragState == STATE_DRAGGING;
1070     }
1071 
1072     /**
1073      * Process a touch event received by the parent view. This method will dispatch callback events
1074      * as needed before returning. The parent view's onTouchEvent implementation should call this.
1075      *
1076      * @param ev The touch event received by the parent view
1077      */
processTouchEvent(MotionEvent ev)1078     public void processTouchEvent(MotionEvent ev) {
1079         final int action = MotionEventCompat.getActionMasked(ev);
1080         final int actionIndex = MotionEventCompat.getActionIndex(ev);
1081 
1082         if (action == MotionEvent.ACTION_DOWN) {
1083             // Reset things for a new event stream, just in case we didn't get
1084             // the whole previous stream.
1085             cancel();
1086         }
1087 
1088         if (mVelocityTracker == null) {
1089             mVelocityTracker = VelocityTracker.obtain();
1090         }
1091         mVelocityTracker.addMovement(ev);
1092 
1093         switch (action) {
1094             case MotionEvent.ACTION_DOWN: {
1095                 final float x = ev.getX();
1096                 final float y = ev.getY();
1097                 final int pointerId = MotionEventCompat.getPointerId(ev, 0);
1098                 final View toCapture = findTopChildUnder((int) x, (int) y);
1099 
1100                 saveInitialMotion(x, y, pointerId);
1101 
1102                 // Since the parent is already directly processing this touch event,
1103                 // there is no reason to delay for a slop before dragging.
1104                 // Start immediately if possible.
1105                 tryCaptureViewForDrag(toCapture, pointerId);
1106 
1107                 final int edgesTouched = mInitialEdgesTouched[pointerId];
1108                 if ((edgesTouched & mTrackingEdges) != 0) {
1109                     mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
1110                 }
1111                 break;
1112             }
1113 
1114             case MotionEventCompat.ACTION_POINTER_DOWN: {
1115                 final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
1116                 final float x = MotionEventCompat.getX(ev, actionIndex);
1117                 final float y = MotionEventCompat.getY(ev, actionIndex);
1118 
1119                 saveInitialMotion(x, y, pointerId);
1120 
1121                 // A ViewDragHelper can only manipulate one view at a time.
1122                 if (mDragState == STATE_IDLE) {
1123                     // If we're idle we can do anything! Treat it like a normal down event.
1124 
1125                     final View toCapture = findTopChildUnder((int) x, (int) y);
1126                     tryCaptureViewForDrag(toCapture, pointerId);
1127 
1128                     final int edgesTouched = mInitialEdgesTouched[pointerId];
1129                     if ((edgesTouched & mTrackingEdges) != 0) {
1130                         mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
1131                     }
1132                 } else if (isCapturedViewUnder((int) x, (int) y)) {
1133                     // We're still tracking a captured view. If the same view is under this
1134                     // point, we'll swap to controlling it with this pointer instead.
1135                     // (This will still work if we're "catching" a settling view.)
1136 
1137                     tryCaptureViewForDrag(mCapturedView, pointerId);
1138                 }
1139                 break;
1140             }
1141 
1142             case MotionEvent.ACTION_MOVE: {
1143                 if (mDragState == STATE_DRAGGING) {
1144                     final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
1145                     final float x = MotionEventCompat.getX(ev, index);
1146                     final float y = MotionEventCompat.getY(ev, index);
1147                     final int idx = (int) (x - mLastMotionX[mActivePointerId]);
1148                     final int idy = (int) (y - mLastMotionY[mActivePointerId]);
1149 
1150                     dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy);
1151 
1152                     saveLastMotion(ev);
1153                 } else {
1154                     // Check to see if any pointer is now over a draggable view.
1155                     final int pointerCount = MotionEventCompat.getPointerCount(ev);
1156                     for (int i = 0; i < pointerCount; i++) {
1157                         final int pointerId = MotionEventCompat.getPointerId(ev, i);
1158                         final float x = MotionEventCompat.getX(ev, i);
1159                         final float y = MotionEventCompat.getY(ev, i);
1160                         final float dx = x - mInitialMotionX[pointerId];
1161                         final float dy = y - mInitialMotionY[pointerId];
1162 
1163                         reportNewEdgeDrags(dx, dy, pointerId);
1164                         if (mDragState == STATE_DRAGGING) {
1165                             // Callback might have started an edge drag.
1166                             break;
1167                         }
1168 
1169                         final View toCapture = findTopChildUnder((int) x, (int) y);
1170                         if (checkTouchSlop(toCapture, dx, dy) &&
1171                                 tryCaptureViewForDrag(toCapture, pointerId)) {
1172                             break;
1173                         }
1174                     }
1175                     saveLastMotion(ev);
1176                 }
1177                 break;
1178             }
1179 
1180             case MotionEventCompat.ACTION_POINTER_UP: {
1181                 final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex);
1182                 if (mDragState == STATE_DRAGGING && pointerId == mActivePointerId) {
1183                     // Try to find another pointer that's still holding on to the captured view.
1184                     int newActivePointer = INVALID_POINTER;
1185                     final int pointerCount = MotionEventCompat.getPointerCount(ev);
1186                     for (int i = 0; i < pointerCount; i++) {
1187                         final int id = MotionEventCompat.getPointerId(ev, i);
1188                         if (id == mActivePointerId) {
1189                             // This one's going away, skip.
1190                             continue;
1191                         }
1192 
1193                         final float x = MotionEventCompat.getX(ev, i);
1194                         final float y = MotionEventCompat.getY(ev, i);
1195                         if (findTopChildUnder((int) x, (int) y) == mCapturedView &&
1196                                 tryCaptureViewForDrag(mCapturedView, id)) {
1197                             newActivePointer = mActivePointerId;
1198                             break;
1199                         }
1200                     }
1201 
1202                     if (newActivePointer == INVALID_POINTER) {
1203                         // We didn't find another pointer still touching the view, release it.
1204                         releaseViewForPointerUp();
1205                     }
1206                 }
1207                 clearMotionHistory(pointerId);
1208                 break;
1209             }
1210 
1211             case MotionEvent.ACTION_UP: {
1212                 if (mDragState == STATE_DRAGGING) {
1213                     releaseViewForPointerUp();
1214                 }
1215                 cancel();
1216                 break;
1217             }
1218 
1219             case MotionEvent.ACTION_CANCEL: {
1220                 if (mDragState == STATE_DRAGGING) {
1221                     dispatchViewReleased(0, 0);
1222                 }
1223                 cancel();
1224                 break;
1225             }
1226         }
1227     }
1228 
reportNewEdgeDrags(float dx, float dy, int pointerId)1229     private void reportNewEdgeDrags(float dx, float dy, int pointerId) {
1230         int dragsStarted = 0;
1231         if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_LEFT)) {
1232             dragsStarted |= EDGE_LEFT;
1233         }
1234         if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_TOP)) {
1235             dragsStarted |= EDGE_TOP;
1236         }
1237         if (checkNewEdgeDrag(dx, dy, pointerId, EDGE_RIGHT)) {
1238             dragsStarted |= EDGE_RIGHT;
1239         }
1240         if (checkNewEdgeDrag(dy, dx, pointerId, EDGE_BOTTOM)) {
1241             dragsStarted |= EDGE_BOTTOM;
1242         }
1243 
1244         if (dragsStarted != 0) {
1245             mEdgeDragsInProgress[pointerId] |= dragsStarted;
1246             mCallback.onEdgeDragStarted(dragsStarted, pointerId);
1247         }
1248     }
1249 
checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge)1250     private boolean checkNewEdgeDrag(float delta, float odelta, int pointerId, int edge) {
1251         final float absDelta = Math.abs(delta);
1252         final float absODelta = Math.abs(odelta);
1253 
1254         if ((mInitialEdgesTouched[pointerId] & edge) != edge  || (mTrackingEdges & edge) == 0 ||
1255                 (mEdgeDragsLocked[pointerId] & edge) == edge ||
1256                 (mEdgeDragsInProgress[pointerId] & edge) == edge ||
1257                 (absDelta <= mTouchSlop && absODelta <= mTouchSlop)) {
1258             return false;
1259         }
1260         if (absDelta < absODelta * 0.5f && mCallback.onEdgeLock(edge)) {
1261             mEdgeDragsLocked[pointerId] |= edge;
1262             return false;
1263         }
1264         return (mEdgeDragsInProgress[pointerId] & edge) == 0 && absDelta > mTouchSlop;
1265     }
1266 
1267     /**
1268      * Check if we've crossed a reasonable touch slop for the given child view.
1269      * If the child cannot be dragged along the horizontal or vertical axis, motion
1270      * along that axis will not count toward the slop check.
1271      *
1272      * @param child Child to check
1273      * @param dx Motion since initial position along X axis
1274      * @param dy Motion since initial position along Y axis
1275      * @return true if the touch slop has been crossed
1276      */
checkTouchSlop(View child, float dx, float dy)1277     private boolean checkTouchSlop(View child, float dx, float dy) {
1278         if (child == null) {
1279             return false;
1280         }
1281         final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0;
1282         final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0;
1283 
1284         if (checkHorizontal && checkVertical) {
1285             return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
1286         } else if (checkHorizontal) {
1287             return Math.abs(dx) > mTouchSlop;
1288         } else if (checkVertical) {
1289             return Math.abs(dy) > mTouchSlop;
1290         }
1291         return false;
1292     }
1293 
1294     /**
1295      * Check if any pointer tracked in the current gesture has crossed
1296      * the required slop threshold.
1297      *
1298      * <p>This depends on internal state populated by
1299      * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
1300      * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on
1301      * the results of this method after all currently available touch data
1302      * has been provided to one of these two methods.</p>
1303      *
1304      * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL},
1305      *                   {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL}
1306      * @return true if the slop threshold has been crossed, false otherwise
1307      */
checkTouchSlop(int directions)1308     public boolean checkTouchSlop(int directions) {
1309         final int count = mInitialMotionX.length;
1310         for (int i = 0; i < count; i++) {
1311             if (checkTouchSlop(directions, i)) {
1312                 return true;
1313             }
1314         }
1315         return false;
1316     }
1317 
1318     /**
1319      * Check if the specified pointer tracked in the current gesture has crossed
1320      * the required slop threshold.
1321      *
1322      * <p>This depends on internal state populated by
1323      * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or
1324      * {@link #processTouchEvent(android.view.MotionEvent)}. You should only rely on
1325      * the results of this method after all currently available touch data
1326      * has been provided to one of these two methods.</p>
1327      *
1328      * @param directions Combination of direction flags, see {@link #DIRECTION_HORIZONTAL},
1329      *                   {@link #DIRECTION_VERTICAL}, {@link #DIRECTION_ALL}
1330      * @param pointerId ID of the pointer to slop check as specified by MotionEvent
1331      * @return true if the slop threshold has been crossed, false otherwise
1332      */
checkTouchSlop(int directions, int pointerId)1333     public boolean checkTouchSlop(int directions, int pointerId) {
1334         if (!isPointerDown(pointerId)) {
1335             return false;
1336         }
1337 
1338         final boolean checkHorizontal = (directions & DIRECTION_HORIZONTAL) == DIRECTION_HORIZONTAL;
1339         final boolean checkVertical = (directions & DIRECTION_VERTICAL) == DIRECTION_VERTICAL;
1340 
1341         final float dx = mLastMotionX[pointerId] - mInitialMotionX[pointerId];
1342         final float dy = mLastMotionY[pointerId] - mInitialMotionY[pointerId];
1343 
1344         if (checkHorizontal && checkVertical) {
1345             return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
1346         } else if (checkHorizontal) {
1347             return Math.abs(dx) > mTouchSlop;
1348         } else if (checkVertical) {
1349             return Math.abs(dy) > mTouchSlop;
1350         }
1351         return false;
1352     }
1353 
1354     /**
1355      * Check if any of the edges specified were initially touched in the currently active gesture.
1356      * If there is no currently active gesture this method will return false.
1357      *
1358      * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT},
1359      *              {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and
1360      *              {@link #EDGE_ALL}
1361      * @return true if any of the edges specified were initially touched in the current gesture
1362      */
isEdgeTouched(int edges)1363     public boolean isEdgeTouched(int edges) {
1364         final int count = mInitialEdgesTouched.length;
1365         for (int i = 0; i < count; i++) {
1366             if (isEdgeTouched(edges, i)) {
1367                 return true;
1368             }
1369         }
1370         return false;
1371     }
1372 
1373     /**
1374      * Check if any of the edges specified were initially touched by the pointer with
1375      * the specified ID. If there is no currently active gesture or if there is no pointer with
1376      * the given ID currently down this method will return false.
1377      *
1378      * @param edges Edges to check for an initial edge touch. See {@link #EDGE_LEFT},
1379      *              {@link #EDGE_TOP}, {@link #EDGE_RIGHT}, {@link #EDGE_BOTTOM} and
1380      *              {@link #EDGE_ALL}
1381      * @return true if any of the edges specified were initially touched in the current gesture
1382      */
isEdgeTouched(int edges, int pointerId)1383     public boolean isEdgeTouched(int edges, int pointerId) {
1384         return isPointerDown(pointerId) && (mInitialEdgesTouched[pointerId] & edges) != 0;
1385     }
1386 
releaseViewForPointerUp()1387     private void releaseViewForPointerUp() {
1388         mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
1389         final float xvel = clampMag(
1390                 VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
1391                 mMinVelocity, mMaxVelocity);
1392         final float yvel = clampMag(
1393                 VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
1394                 mMinVelocity, mMaxVelocity);
1395         dispatchViewReleased(xvel, yvel);
1396     }
1397 
dragTo(int left, int top, int dx, int dy)1398     private void dragTo(int left, int top, int dx, int dy) {
1399         int clampedX = left;
1400         int clampedY = top;
1401         final int oldLeft = mCapturedView.getLeft();
1402         final int oldTop = mCapturedView.getTop();
1403         if (dx != 0) {
1404             clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
1405             mCapturedView.offsetLeftAndRight(clampedX - oldLeft);
1406         }
1407         if (dy != 0) {
1408             clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
1409             mCapturedView.offsetTopAndBottom(clampedY - oldTop);
1410         }
1411 
1412         if (dx != 0 || dy != 0) {
1413             final int clampedDx = clampedX - oldLeft;
1414             final int clampedDy = clampedY - oldTop;
1415             mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY,
1416                     clampedDx, clampedDy);
1417         }
1418     }
1419 
1420     /**
1421      * Determine if the currently captured view is under the given point in the
1422      * parent view's coordinate system. If there is no captured view this method
1423      * will return false.
1424      *
1425      * @param x X position to test in the parent's coordinate system
1426      * @param y Y position to test in the parent's coordinate system
1427      * @return true if the captured view is under the given point, false otherwise
1428      */
isCapturedViewUnder(int x, int y)1429     public boolean isCapturedViewUnder(int x, int y) {
1430         return isViewUnder(mCapturedView, x, y);
1431     }
1432 
1433     /**
1434      * Determine if the supplied view is under the given point in the
1435      * parent view's coordinate system.
1436      *
1437      * @param view Child view of the parent to hit test
1438      * @param x X position to test in the parent's coordinate system
1439      * @param y Y position to test in the parent's coordinate system
1440      * @return true if the supplied view is under the given point, false otherwise
1441      */
isViewUnder(View view, int x, int y)1442     public boolean isViewUnder(View view, int x, int y) {
1443         if (view == null) {
1444             return false;
1445         }
1446         return x >= view.getLeft() &&
1447                 x < view.getRight() &&
1448                 y >= view.getTop() &&
1449                 y < view.getBottom();
1450     }
1451 
1452     /**
1453      * Find the topmost child under the given point within the parent view's coordinate system.
1454      * The child order is determined using {@link Callback#getOrderedChildIndex(int)}.
1455      *
1456      * @param x X position to test in the parent's coordinate system
1457      * @param y Y position to test in the parent's coordinate system
1458      * @return The topmost child view under (x, y) or null if none found.
1459      */
findTopChildUnder(int x, int y)1460     public View findTopChildUnder(int x, int y) {
1461         final int childCount = mParentView.getChildCount();
1462         for (int i = childCount - 1; i >= 0; i--) {
1463             final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
1464             if (x >= child.getLeft() && x < child.getRight() &&
1465                     y >= child.getTop() && y < child.getBottom()) {
1466                 return child;
1467             }
1468         }
1469         return null;
1470     }
1471 
getEdgesTouched(int x, int y)1472     private int getEdgesTouched(int x, int y) {
1473         int result = 0;
1474 
1475         if (x < mParentView.getLeft() + mEdgeSize) result |= EDGE_LEFT;
1476         if (y < mParentView.getTop() + mEdgeSize) result |= EDGE_TOP;
1477         if (x > mParentView.getRight() - mEdgeSize) result |= EDGE_RIGHT;
1478         if (y > mParentView.getBottom() - mEdgeSize) result |= EDGE_BOTTOM;
1479 
1480         return result;
1481     }
1482 }