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