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