on*
methods are invoked on siginficant events and several
145 | * accessor methods are expected to provide the ViewDragHelper with more information
146 | * about the state of the parent view upon request. The callback also makes decisions
147 | * governing the range and draggability of child views.
148 | */
149 | public static abstract class Callback {
150 | /**
151 | * Called when the drag state changes. See the STATE_*
constants
152 | * for more information.
153 | *
154 | * @param state The new drag state
155 | *
156 | * @see #STATE_IDLE
157 | * @see #STATE_DRAGGING
158 | * @see #STATE_SETTLING
159 | */
160 | public void onViewDragStateChanged(int state) {}
161 |
162 | /**
163 | * Called when the captured view's position changes as the result of a drag or settle.
164 | *
165 | * @param changedView View whose position changed
166 | * @param left New X coordinate of the left edge of the view
167 | * @param top New Y coordinate of the top edge of the view
168 | * @param dx Change in X position from the last call
169 | * @param dy Change in Y position from the last call
170 | */
171 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {}
172 |
173 | /**
174 | * Called when a child view is captured for dragging or settling. The ID of the pointer
175 | * currently dragging the captured view is supplied. If activePointerId is
176 | * identified as {@link #INVALID_POINTER} the capture is programmatic instead of
177 | * pointer-initiated.
178 | *
179 | * @param capturedChild Child view that was captured
180 | * @param activePointerId Pointer id tracking the child capture
181 | */
182 | public void onViewCaptured(View capturedChild, int activePointerId) {}
183 |
184 | /**
185 | * Called when the child view is no longer being actively dragged.
186 | * The fling velocity is also supplied, if relevant. The velocity values may
187 | * be clamped to system minimums or maximums.
188 | *
189 | * Calling code may decide to fling or otherwise release the view to let it
190 | * settle into place. It should do so using {@link #settleCapturedViewAt(int, int)}
191 | * or {@link #flingCapturedView(int, int, int, int)}. If the Callback invokes
192 | * one of these methods, the ViewDragHelper will enter {@link #STATE_SETTLING}
193 | * and the view capture will not fully end until it comes to a complete stop.
194 | * If neither of these methods is invoked before onViewReleased
returns,
195 | * the view will stop in place and the ViewDragHelper will return to
196 | * {@link #STATE_IDLE}.
index
248 | */
249 | public int getOrderedChildIndex(int index) {
250 | return index;
251 | }
252 |
253 | /**
254 | * Return the magnitude of a draggable child view's horizontal range of motion in pixels.
255 | * This method should return 0 for views that cannot move horizontally.
256 | *
257 | * @param child Child view to check
258 | * @return range of horizontal motion in pixels
259 | */
260 | public int getViewHorizontalDragRange(View child) {
261 | return 0;
262 | }
263 |
264 | /**
265 | * Return the magnitude of a draggable child view's vertical range of motion in pixels.
266 | * This method should return 0 for views that cannot move vertically.
267 | *
268 | * @param child Child view to check
269 | * @return range of vertical motion in pixels
270 | */
271 | public int getViewVerticalDragRange(View child) {
272 | return 0;
273 | }
274 |
275 | /**
276 | * Called when the user's input indicates that they want to capture the given child view
277 | * with the pointer indicated by pointerId. The callback should return true if the user
278 | * is permitted to drag the given view with the indicated pointer.
279 | *
280 | * ViewDragHelper may call this method multiple times for the same view even if 281 | * the view is already captured; this indicates that a new pointer is trying to take 282 | * control of the view.
283 | * 284 | *If this method returns true, a call to {@link #onViewCaptured(android.view.View, int)} 285 | * will follow if the capture is successful.
286 | * 287 | * @param child Child the user is attempting to capture 288 | * @param pointerId ID of the pointer attempting the capture 289 | * @return true if capture should be allowed, false otherwise 290 | */ 291 | public abstract boolean tryCaptureView(View child, int pointerId); 292 | 293 | /** 294 | * Restrict the motion of the dragged child view along the horizontal axis. 295 | * The default implementation does not allow horizontal motion; the extending 296 | * class must override this method and provide the desired clamping. 297 | * 298 | * 299 | * @param child Child view being dragged 300 | * @param left Attempted motion along the X axis 301 | * @param dx Proposed change in position for left 302 | * @return The new clamped position for left 303 | */ 304 | public int clampViewPositionHorizontal(View child, int left, int dx) { 305 | return 0; 306 | } 307 | 308 | /** 309 | * Restrict the motion of the dragged child view along the vertical axis. 310 | * The default implementation does not allow vertical motion; the extending 311 | * class must override this method and provide the desired clamping. 312 | * 313 | * 314 | * @param child Child view being dragged 315 | * @param top Attempted motion along the Y axis 316 | * @param dy Proposed change in position for top 317 | * @return The new clamped position for top 318 | */ 319 | public int clampViewPositionVertical(View child, int top, int dy) { 320 | return 0; 321 | } 322 | } 323 | 324 | /** 325 | * Interpolator defining the animation curve for mScroller 326 | */ 327 | private static final Interpolator sInterpolator = new Interpolator() { 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 | public void run() { 336 | setDragState(STATE_IDLE); 337 | } 338 | }; 339 | 340 | /** 341 | * Factory method to create a new ViewDragHelper. 342 | * 343 | * @param forParent Parent view to monitor 344 | * @param cb Callback to provide information and receive events 345 | * @return a new ViewDragHelper instance 346 | */ 347 | public static ViewDragHelper create(ViewGroup forParent, Callback cb) { 348 | return new ViewDragHelper(forParent.getContext(), forParent, cb); 349 | } 350 | 351 | /** 352 | * Factory method to create a new ViewDragHelper. 353 | * 354 | * @param forParent Parent view to monitor 355 | * @param sensitivity Multiplier for how sensitive the helper should be about detecting 356 | * the start of a drag. Larger values are more sensitive. 1.0f is normal. 357 | * @param cb Callback to provide information and receive events 358 | * @return a new ViewDragHelper instance 359 | */ 360 | public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) { 361 | final ViewDragHelper helper = create(forParent, cb); 362 | helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity)); 363 | return helper; 364 | } 365 | 366 | /** 367 | * Apps should use ViewDragHelper.create() to get a new instance. 368 | * This will allow VDH to use internal compatibility implementations for different 369 | * platform versions. 370 | * 371 | * @param context Context to initialize config-dependent params from 372 | * @param forParent Parent view to monitor 373 | */ 374 | private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) { 375 | if (forParent == null) { 376 | throw new IllegalArgumentException("Parent view may not be null"); 377 | } 378 | if (cb == null) { 379 | throw new IllegalArgumentException("Callback may not be null"); 380 | } 381 | 382 | mParentView = forParent; 383 | mCallback = cb; 384 | 385 | final ViewConfiguration vc = ViewConfiguration.get(context); 386 | final float density = context.getResources().getDisplayMetrics().density; 387 | mEdgeSize = (int) (EDGE_SIZE * density + 0.5f); 388 | 389 | mTouchSlop = vc.getScaledTouchSlop(); 390 | mMaxVelocity = vc.getScaledMaximumFlingVelocity(); 391 | mMinVelocity = vc.getScaledMinimumFlingVelocity(); 392 | mScroller = ScrollerCompat.create(context, sInterpolator); 393 | } 394 | 395 | /** 396 | * Set the minimum velocity that will be detected as having a magnitude greater than zero 397 | * in pixels per second. Callback methods accepting a velocity will be clamped appropriately. 398 | * 399 | * @param minVel Minimum velocity to detect 400 | */ 401 | public void setMinVelocity(float minVel) { 402 | mMinVelocity = minVel; 403 | } 404 | 405 | /** 406 | * Return the currently configured minimum velocity. Any flings with a magnitude less 407 | * than this value in pixels per second. Callback methods accepting a velocity will receive 408 | * zero as a velocity value if the real detected velocity was below this threshold. 409 | * 410 | * @return the minimum velocity that will be detected 411 | */ 412 | public float getMinVelocity() { 413 | return mMinVelocity; 414 | } 415 | 416 | /** 417 | * Retrieve the current drag state of this helper. This will return one of 418 | * {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}. 419 | * @return The current drag state 420 | */ 421 | public int getViewDragState() { 422 | return mDragState; 423 | } 424 | 425 | /** 426 | * Enable edge tracking for the selected edges of the parent view. 427 | * The callback's {@link com.laowch.pulltoback.ViewDragHelper.Callback#onEdgeTouched(int, int)} and 428 | * {@link com.laowch.pulltoback.ViewDragHelper.Callback#onEdgeDragStarted(int, int)} methods will only be invoked 429 | * for edges for which edge tracking has been enabled. 430 | * 431 | * @param edgeFlags Combination of edge flags describing the edges to watch 432 | * @see #EDGE_LEFT 433 | * @see #EDGE_TOP 434 | * @see #EDGE_RIGHT 435 | * @see #EDGE_BOTTOM 436 | */ 437 | public void setEdgeTrackingEnabled(int edgeFlags) { 438 | mTrackingEdges = edgeFlags; 439 | } 440 | 441 | /** 442 | * Return the size of an edge. This is the range in pixels along the edges of this view 443 | * that will actively detect edge touches or drags if edge tracking is enabled. 444 | * 445 | * @return The size of an edge in pixels 446 | * @see #setEdgeTrackingEnabled(int) 447 | */ 448 | public int getEdgeSize() { 449 | return mEdgeSize; 450 | } 451 | 452 | /** 453 | * Capture a specific child view for dragging within the parent. The callback will be notified 454 | * but {@link com.laowch.pulltoback.ViewDragHelper.Callback#tryCaptureView(android.view.View, int)} will not be asked permission to 455 | * capture this view. 456 | * 457 | * @param childView Child view to capture 458 | * @param activePointerId ID of the pointer that is dragging the captured child view 459 | */ 460 | public void captureChildView(View childView, int activePointerId) { 461 | if (childView.getParent() != mParentView) { 462 | throw new IllegalArgumentException("captureChildView: parameter must be a descendant " + 463 | "of the ViewDragHelper's tracked parent view (" + mParentView + ")"); 464 | } 465 | 466 | mCapturedView = childView; 467 | mActivePointerId = activePointerId; 468 | mCallback.onViewCaptured(childView, activePointerId); 469 | setDragState(STATE_DRAGGING); 470 | } 471 | 472 | /** 473 | * @return The currently captured view, or null if no view has been captured. 474 | */ 475 | public View getCapturedView() { 476 | return mCapturedView; 477 | } 478 | 479 | /** 480 | * @return The ID of the pointer currently dragging the captured view, 481 | * or {@link #INVALID_POINTER}. 482 | */ 483 | public int getActivePointerId() { 484 | return mActivePointerId; 485 | } 486 | 487 | /** 488 | * @return The minimum distance in pixels that the user must travel to initiate a drag 489 | */ 490 | public int getTouchSlop() { 491 | return mTouchSlop; 492 | } 493 | 494 | /** 495 | * The result of a call to this method is equivalent to 496 | * {@link #processTouchEvent(android.view.MotionEvent)} receiving an ACTION_CANCEL event. 497 | */ 498 | public void cancel() { 499 | mActivePointerId = INVALID_POINTER; 500 | clearMotionHistory(); 501 | 502 | if (mVelocityTracker != null) { 503 | mVelocityTracker.recycle(); 504 | mVelocityTracker = null; 505 | } 506 | 507 | if (mInitialMotionX != null) { 508 | mInitialMotionX = null; 509 | } 510 | } 511 | 512 | /** 513 | * {@link #cancel()}, but also abort all motion in progress and snap to the end of any 514 | * animation. 515 | */ 516 | public void abort() { 517 | cancel(); 518 | if (mDragState == STATE_SETTLING) { 519 | final int oldX = mScroller.getCurrX(); 520 | final int oldY = mScroller.getCurrY(); 521 | mScroller.abortAnimation(); 522 | final int newX = mScroller.getCurrX(); 523 | final int newY = mScroller.getCurrY(); 524 | mCallback.onViewPositionChanged(mCapturedView, newX, newY, newX - oldX, newY - oldY); 525 | } 526 | setDragState(STATE_IDLE); 527 | } 528 | 529 | /** 530 | * Animate the viewchild
to the given (left, top) position.
531 | * If this method returns true, the caller should invoke {@link #continueSettling(boolean)}
532 | * on each subsequent frame to continue the motion until it returns false. If this method
533 | * returns false there is no further work to do to complete the movement.
534 | *
535 | * This operation does not count as a capture event, though {@link #getCapturedView()} 536 | * will still report the sliding view while the slide is in progress.
537 | * 538 | * @param child Child view to capture and animate 539 | * @param finalLeft Final left position of child 540 | * @param finalTop Final top position of child 541 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 542 | */ 543 | public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) { 544 | mCapturedView = child; 545 | mActivePointerId = INVALID_POINTER; 546 | 547 | boolean continueSliding = forceSettleCapturedViewAt(finalLeft, finalTop, 0, 0); 548 | if (!continueSliding && mDragState == STATE_IDLE && mCapturedView != null) { 549 | // If we're in an IDLE state to begin with and aren't moving anywhere, we 550 | // end up having a non-null capturedView with an IDLE dragState 551 | mCapturedView = null; 552 | } 553 | 554 | return continueSliding; 555 | } 556 | 557 | /** 558 | * Settle the captured view at the given (left, top) position. 559 | * The appropriate velocity from prior motion will be taken into account. 560 | * If this method returns true, the caller should invoke {@link #continueSettling(boolean)} 561 | * on each subsequent frame to continue the motion until it returns false. If this method 562 | * returns false there is no further work to do to complete the movement. 563 | * 564 | * @param finalLeft Settled left edge position for the captured view 565 | * @param finalTop Settled top edge position for the captured view 566 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 567 | */ 568 | public boolean settleCapturedViewAt(int finalLeft, int finalTop) { 569 | if (!mReleaseInProgress) { 570 | throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to " + 571 | "Callback#onViewReleased"); 572 | } 573 | 574 | return forceSettleCapturedViewAt(finalLeft, finalTop, 575 | (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), 576 | (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId)); 577 | } 578 | 579 | /** 580 | * Settle the captured view at the given (left, top) position. 581 | * 582 | * @param finalLeft Target left position for the captured view 583 | * @param finalTop Target top position for the captured view 584 | * @param xvel Horizontal velocity 585 | * @param yvel Vertical velocity 586 | * @return true if animation should continue through {@link #continueSettling(boolean)} calls 587 | */ 588 | private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) { 589 | final int startLeft = mCapturedView.getLeft(); 590 | final int startTop = mCapturedView.getTop(); 591 | final int dx = finalLeft - startLeft; 592 | final int dy = finalTop - startTop; 593 | 594 | if (dx == 0 && dy == 0) { 595 | // Nothing to do. Send callbacks, be done. 596 | mScroller.abortAnimation(); 597 | setDragState(STATE_IDLE); 598 | return false; 599 | } 600 | 601 | final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel); 602 | mScroller.startScroll(startLeft, startTop, dx, dy, duration); 603 | 604 | setDragState(STATE_SETTLING); 605 | return true; 606 | } 607 | 608 | private int computeSettleDuration(View child, int dx, int dy, int xvel, int yvel) { 609 | xvel = clampMag(xvel, (int) mMinVelocity, (int) mMaxVelocity); 610 | yvel = clampMag(yvel, (int) mMinVelocity, (int) mMaxVelocity); 611 | final int absDx = Math.abs(dx); 612 | final int absDy = Math.abs(dy); 613 | final int absXVel = Math.abs(xvel); 614 | final int absYVel = Math.abs(yvel); 615 | final int addedVel = absXVel + absYVel; 616 | final int addedDistance = absDx + absDy; 617 | 618 | final float xweight = xvel != 0 ? (float) absXVel / addedVel : 619 | (float) absDx / addedDistance; 620 | final float yweight = yvel != 0 ? (float) absYVel / addedVel : 621 | (float) absDy / addedDistance; 622 | 623 | int xduration = computeAxisDuration(dx, xvel, mCallback.getViewHorizontalDragRange(child)); 624 | int yduration = computeAxisDuration(dy, yvel, mCallback.getViewVerticalDragRange(child)); 625 | 626 | return (int) (xduration * xweight + yduration * yweight); 627 | } 628 | 629 | private int computeAxisDuration(int delta, int velocity, int motionRange) { 630 | if (delta == 0) { 631 | return 0; 632 | } 633 | 634 | final int width = mParentView.getWidth(); 635 | final int halfWidth = width / 2; 636 | final float distanceRatio = Math.min(1f, (float) Math.abs(delta) / width); 637 | final float distance = halfWidth + halfWidth * 638 | distanceInfluenceForSnapDuration(distanceRatio); 639 | 640 | int duration; 641 | velocity = Math.abs(velocity); 642 | if (velocity > 0) { 643 | duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); 644 | } else { 645 | final float range = (float) Math.abs(delta) / motionRange; 646 | duration = (int) ((range + 1) * BASE_SETTLE_DURATION); 647 | } 648 | return Math.min(duration, MAX_SETTLE_DURATION); 649 | } 650 | 651 | /** 652 | * Clamp the magnitude of value for absMin and absMax. 653 | * If the value is below the minimum, it will be clamped to zero. 654 | * If the value is above the maximum, it will be clamped to the maximum. 655 | * 656 | * @param value Value to clamp 657 | * @param absMin Absolute value of the minimum significant value to return 658 | * @param absMax Absolute value of the maximum value to return 659 | * @return The clamped value with the same sign asvalue
660 | */
661 | private int clampMag(int value, int absMin, int absMax) {
662 | final int absValue = Math.abs(value);
663 | if (absValue < absMin) return 0;
664 | if (absValue > absMax) return value > 0 ? absMax : -absMax;
665 | return value;
666 | }
667 |
668 | /**
669 | * Clamp the magnitude of value for absMin and absMax.
670 | * If the value is below the minimum, it will be clamped to zero.
671 | * If the value is above the maximum, it will be clamped to the maximum.
672 | *
673 | * @param value Value to clamp
674 | * @param absMin Absolute value of the minimum significant value to return
675 | * @param absMax Absolute value of the maximum value to return
676 | * @return The clamped value with the same sign as value
677 | */
678 | private float clampMag(float value, float absMin, float absMax) {
679 | final float absValue = Math.abs(value);
680 | if (absValue < absMin) return 0;
681 | if (absValue > absMax) return value > 0 ? absMax : -absMax;
682 | return value;
683 | }
684 |
685 | private float distanceInfluenceForSnapDuration(float f) {
686 | f -= 0.5f; // center the values about 0.
687 | f *= 0.3f * Math.PI / 2.0f;
688 | return (float) Math.sin(f);
689 | }
690 |
691 | /**
692 | * Settle the captured view based on standard free-moving fling behavior.
693 | * The caller should invoke {@link #continueSettling(boolean)} on each subsequent frame
694 | * to continue the motion until it returns false.
695 | *
696 | * @param minLeft Minimum X position for the view's left edge
697 | * @param minTop Minimum Y position for the view's top edge
698 | * @param maxLeft Maximum X position for the view's left edge
699 | * @param maxTop Maximum Y position for the view's top edge
700 | */
701 | public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {
702 | if (!mReleaseInProgress) {
703 | throw new IllegalStateException("Cannot flingCapturedView outside of a call to " +
704 | "Callback#onViewReleased");
705 | }
706 |
707 | mScroller.fling(mCapturedView.getLeft(), mCapturedView.getTop(),
708 | (int) VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId),
709 | (int) VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId),
710 | minLeft, maxLeft, minTop, maxTop);
711 |
712 | setDragState(STATE_SETTLING);
713 | }
714 |
715 | /**
716 | * Move the captured settling view by the appropriate amount for the current time.
717 | * If continueSettling
returns true, the caller should call it again
718 | * on the next frame to continue.
719 | *
720 | * @param deferCallbacks true if state callbacks should be deferred via posted message.
721 | * Set this to true if you are calling this method from
722 | * {@link android.view.View#computeScroll()} or similar methods
723 | * invoked as part of layout or drawing.
724 | * @return true if settle is still in progress
725 | */
726 | public boolean continueSettling(boolean deferCallbacks) {
727 | if (mDragState == STATE_SETTLING) {
728 | boolean keepGoing = mScroller.computeScrollOffset();
729 | final int x = mScroller.getCurrX();
730 | final int y = mScroller.getCurrY();
731 | final int dx = x - mCapturedView.getLeft();
732 | final int dy = y - mCapturedView.getTop();
733 |
734 | if (dx != 0) {
735 | mCapturedView.offsetLeftAndRight(dx);
736 | }
737 | if (dy != 0) {
738 | mCapturedView.offsetTopAndBottom(dy);
739 | }
740 |
741 | if (dx != 0 || dy != 0) {
742 | mCallback.onViewPositionChanged(mCapturedView, x, y, dx, dy);
743 | }
744 |
745 | if (keepGoing && x == mScroller.getFinalX() && y == mScroller.getFinalY()) {
746 | // Close enough. The interpolator/scroller might think we're still moving
747 | // but the user sure doesn't.
748 | mScroller.abortAnimation();
749 | keepGoing = false;
750 | }
751 |
752 | if (!keepGoing) {
753 | if (deferCallbacks) {
754 | mParentView.post(mSetIdleRunnable);
755 | } else {
756 | setDragState(STATE_IDLE);
757 | }
758 | }
759 | }
760 |
761 | return mDragState == STATE_SETTLING;
762 | }
763 |
764 | /**
765 | * Like all callback events this must happen on the UI thread, but release
766 | * involves some extra semantics. During a release (mReleaseInProgress)
767 | * is the only time it is valid to call {@link #settleCapturedViewAt(int, int)}
768 | * or {@link #flingCapturedView(int, int, int, int)}.
769 | */
770 | private void dispatchViewReleased(float xvel, float yvel) {
771 | mReleaseInProgress = true;
772 | mCallback.onViewReleased(mCapturedView, xvel, yvel);
773 | mReleaseInProgress = false;
774 |
775 | if (mDragState == STATE_DRAGGING) {
776 | // onViewReleased didn't call a method that would have changed this. Go idle.
777 | setDragState(STATE_IDLE);
778 | }
779 | }
780 |
781 | private void clearMotionHistory() {
782 | if (mInitialMotionX == null) {
783 | return;
784 | }
785 | Arrays.fill(mInitialMotionX, 0);
786 | Arrays.fill(mInitialMotionY, 0);
787 | Arrays.fill(mLastMotionX, 0);
788 | Arrays.fill(mLastMotionY, 0);
789 | Arrays.fill(mInitialEdgesTouched, 0);
790 | Arrays.fill(mEdgeDragsInProgress, 0);
791 | Arrays.fill(mEdgeDragsLocked, 0);
792 | mPointersDown = 0;
793 | }
794 |
795 | private void clearMotionHistory(int pointerId) {
796 | if (mInitialMotionX == null) {
797 | return;
798 | }
799 | mInitialMotionX[pointerId] = 0;
800 | mInitialMotionY[pointerId] = 0;
801 | mLastMotionX[pointerId] = 0;
802 | mLastMotionY[pointerId] = 0;
803 | mInitialEdgesTouched[pointerId] = 0;
804 | mEdgeDragsInProgress[pointerId] = 0;
805 | mEdgeDragsLocked[pointerId] = 0;
806 | mPointersDown &= ~(1 << pointerId);
807 | }
808 |
809 | private void ensureMotionHistorySizeForId(int pointerId) {
810 | if (mInitialMotionX == null || mInitialMotionX.length <= pointerId) {
811 | float[] imx = new float[pointerId + 1];
812 | float[] imy = new float[pointerId + 1];
813 | float[] lmx = new float[pointerId + 1];
814 | float[] lmy = new float[pointerId + 1];
815 | int[] iit = new int[pointerId + 1];
816 | int[] edip = new int[pointerId + 1];
817 | int[] edl = new int[pointerId + 1];
818 |
819 | if (mInitialMotionX != null) {
820 | System.arraycopy(mInitialMotionX, 0, imx, 0, mInitialMotionX.length);
821 | System.arraycopy(mInitialMotionY, 0, imy, 0, mInitialMotionY.length);
822 | System.arraycopy(mLastMotionX, 0, lmx, 0, mLastMotionX.length);
823 | System.arraycopy(mLastMotionY, 0, lmy, 0, mLastMotionY.length);
824 | System.arraycopy(mInitialEdgesTouched, 0, iit, 0, mInitialEdgesTouched.length);
825 | System.arraycopy(mEdgeDragsInProgress, 0, edip, 0, mEdgeDragsInProgress.length);
826 | System.arraycopy(mEdgeDragsLocked, 0, edl, 0, mEdgeDragsLocked.length);
827 | }
828 |
829 | mInitialMotionX = imx;
830 | mInitialMotionY = imy;
831 | mLastMotionX = lmx;
832 | mLastMotionY = lmy;
833 | mInitialEdgesTouched = iit;
834 | mEdgeDragsInProgress = edip;
835 | mEdgeDragsLocked = edl;
836 | }
837 | }
838 |
839 | private void saveInitialMotion(float x, float y, int pointerId) {
840 | ensureMotionHistorySizeForId(pointerId);
841 | mInitialMotionX[pointerId] = mLastMotionX[pointerId] = x;
842 | mInitialMotionY[pointerId] = mLastMotionY[pointerId] = y;
843 | mInitialEdgesTouched[pointerId] = getEdgesTouched((int) x, (int) y);
844 | mPointersDown |= 1 << pointerId;
845 | }
846 |
847 | private void saveLastMotion(MotionEvent ev) {
848 | final int pointerCount = MotionEventCompat.getPointerCount(ev);
849 | for (int i = 0; i < pointerCount; i++) {
850 | final int pointerId = MotionEventCompat.getPointerId(ev, i);
851 | final float x = MotionEventCompat.getX(ev, i);
852 | final float y = MotionEventCompat.getY(ev, i);
853 | mLastMotionX[pointerId] = x;
854 | mLastMotionY[pointerId] = y;
855 | }
856 | }
857 |
858 | /**
859 | * Check if the given pointer ID represents a pointer that is currently down (to the best
860 | * of the ViewDragHelper's knowledge).
861 | *
862 | * The state used to report this information is populated by the methods 863 | * {@link #shouldInterceptTouchEvent(android.view.MotionEvent)} or 864 | * {@link #processTouchEvent(android.view.MotionEvent)}. If one of these methods has not 865 | * been called for all relevant MotionEvents to track, the information reported 866 | * by this method may be stale or incorrect.
867 | * 868 | * @param pointerId pointer ID to check; corresponds to IDs provided by MotionEvent 869 | * @return true if the pointer with the given ID is still down 870 | */ 871 | public boolean isPointerDown(int pointerId) { 872 | return (mPointersDown & 1 << pointerId) != 0; 873 | } 874 | 875 | void setDragState(int state) { 876 | if (mDragState != state) { 877 | mDragState = state; 878 | mCallback.onViewDragStateChanged(state); 879 | if (mDragState == STATE_IDLE) { 880 | mCapturedView = null; 881 | } 882 | } 883 | } 884 | 885 | /** 886 | * Attempt to capture the view with the given pointer ID. The callback will be involved. 887 | * This will put us into the "dragging" state. If we've already captured this view with 888 | * this pointer this method will immediately return true without consulting the callback. 889 | * 890 | * @param toCapture View to capture 891 | * @param pointerId Pointer to capture with 892 | * @return true if capture was successful 893 | */ 894 | boolean tryCaptureViewForDrag(View toCapture, int pointerId) { 895 | if (toCapture == mCapturedView && mActivePointerId == pointerId) { 896 | // Already done! 897 | return true; 898 | } 899 | if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) { 900 | mActivePointerId = pointerId; 901 | captureChildView(toCapture, pointerId); 902 | return true; 903 | } 904 | return false; 905 | } 906 | 907 | /** 908 | * Tests scrollability within child views of v given a delta of dx. 909 | * 910 | * @param v View to test for horizontal scrollability 911 | * @param checkV Whether the view v passed should itself be checked for scrollability (true), 912 | * or just its children (false). 913 | * @param dx Delta scrolled in pixels along the X axis 914 | * @param dy Delta scrolled in pixels along the Y axis 915 | * @param x X coordinate of the active touch point 916 | * @param y Y coordinate of the active touch point 917 | * @return true if child views of v can be scrolled by delta of dx. 918 | */ 919 | protected boolean canScroll(View v, boolean checkV, int dx, int dy, int x, int y) { 920 | if (v instanceof ViewGroup) { 921 | final ViewGroup group = (ViewGroup) v; 922 | final int scrollX = v.getScrollX(); 923 | final int scrollY = v.getScrollY(); 924 | final int count = group.getChildCount(); 925 | // Count backwards - let topmost views consume scroll distance first. 926 | for (int i = count - 1; i >= 0; i--) { 927 | // TODO: Add versioned support here for transformed views. 928 | // This will not work for transformed views in Honeycomb+ 929 | final View child = group.getChildAt(i); 930 | if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && 931 | y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && 932 | canScroll(child, true, dx, dy, x + scrollX - child.getLeft(), 933 | y + scrollY - child.getTop())) { 934 | return true; 935 | } 936 | } 937 | } 938 | 939 | return checkV && (ViewCompat.canScrollHorizontally(v, -dx) || 940 | ViewCompat.canScrollVertically(v, -dy)); 941 | } 942 | 943 | /** 944 | * Check if this event as provided to the parent view's onInterceptTouchEvent should 945 | * cause the parent to intercept the touch event stream. 946 | * 947 | * @param ev MotionEvent provided to onInterceptTouchEvent 948 | * @return true if the parent view should return true from onInterceptTouchEvent 949 | */ 950 | public boolean shouldInterceptTouchEvent(MotionEvent ev) { 951 | final int action = MotionEventCompat.getActionMasked(ev); 952 | final int actionIndex = MotionEventCompat.getActionIndex(ev); 953 | 954 | if (action == MotionEvent.ACTION_DOWN) { 955 | // Reset things for a new event stream, just in case we didn't get 956 | // the whole previous stream. 957 | cancel(); 958 | } 959 | 960 | if (mVelocityTracker == null) { 961 | mVelocityTracker = VelocityTracker.obtain(); 962 | } 963 | mVelocityTracker.addMovement(ev); 964 | 965 | switch (action) { 966 | case MotionEvent.ACTION_DOWN: { 967 | final float x = ev.getX(); 968 | final float y = ev.getY(); 969 | final int pointerId = MotionEventCompat.getPointerId(ev, 0); 970 | saveInitialMotion(x, y, pointerId); 971 | 972 | final View toCapture = findTopChildUnder((int) x, (int) y); 973 | 974 | // Catch a settling view if possible. 975 | if (toCapture == mCapturedView && mDragState == STATE_SETTLING) { 976 | tryCaptureViewForDrag(toCapture, pointerId); 977 | } 978 | 979 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 980 | if ((edgesTouched & mTrackingEdges) != 0) { 981 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 982 | } 983 | break; 984 | } 985 | 986 | case MotionEventCompat.ACTION_POINTER_DOWN: { 987 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 988 | final float x = MotionEventCompat.getX(ev, actionIndex); 989 | final float y = MotionEventCompat.getY(ev, actionIndex); 990 | 991 | saveInitialMotion(x, y, pointerId); 992 | 993 | // A ViewDragHelper can only manipulate one view at a time. 994 | if (mDragState == STATE_IDLE) { 995 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 996 | if ((edgesTouched & mTrackingEdges) != 0) { 997 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 998 | } 999 | } else if (mDragState == STATE_SETTLING) { 1000 | // Catch a settling view if possible. 1001 | final View toCapture = findTopChildUnder((int) x, (int) y); 1002 | if (toCapture == mCapturedView) { 1003 | tryCaptureViewForDrag(toCapture, pointerId); 1004 | } 1005 | } 1006 | break; 1007 | } 1008 | 1009 | case MotionEvent.ACTION_MOVE: { 1010 | if (mInitialMotionX == null) { 1011 | return false; 1012 | } 1013 | 1014 | // First to cross a touch slop over a draggable view wins. Also report edge drags. 1015 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 1016 | for (int i = 0; i < pointerCount; i++) { 1017 | final int pointerId = MotionEventCompat.getPointerId(ev, i); 1018 | final float x = MotionEventCompat.getX(ev, i); 1019 | final float y = MotionEventCompat.getY(ev, i); 1020 | final float dx = x - mInitialMotionX[pointerId]; 1021 | final float dy = y - mInitialMotionY[pointerId]; 1022 | 1023 | final View toCapture = findTopChildUnder((int) x, (int) y); 1024 | final boolean pastSlop = toCapture != null && checkTouchSlop(toCapture, dx, dy); 1025 | if (pastSlop) { 1026 | // check the callback's 1027 | // getView[Horizontal|Vertical]DragRange methods to know 1028 | // if you can move at all along an axis, then see if it 1029 | // would clamp to the same value. If you can't move at 1030 | // all in every dimension with a nonzero range, bail. 1031 | final int oldLeft = toCapture.getLeft(); 1032 | final int targetLeft = oldLeft + (int) dx; 1033 | final int newLeft = mCallback.clampViewPositionHorizontal(toCapture, 1034 | targetLeft, (int) dx); 1035 | final int oldTop = toCapture.getTop(); 1036 | final int targetTop = oldTop + (int) dy; 1037 | final int newTop = mCallback.clampViewPositionVertical(toCapture, targetTop, 1038 | (int) dy); 1039 | final int horizontalDragRange = mCallback.getViewHorizontalDragRange( 1040 | toCapture); 1041 | final int verticalDragRange = mCallback.getViewVerticalDragRange(toCapture); 1042 | if ((horizontalDragRange == 0 || horizontalDragRange > 0 1043 | && newLeft == oldLeft) && (verticalDragRange == 0 1044 | || verticalDragRange > 0 && newTop == oldTop)) { 1045 | break; 1046 | } 1047 | } 1048 | reportNewEdgeDrags(dx, dy, pointerId); 1049 | if (mDragState == STATE_DRAGGING) { 1050 | // Callback might have started an edge drag 1051 | break; 1052 | } 1053 | 1054 | if (pastSlop && tryCaptureViewForDrag(toCapture, pointerId)) { 1055 | break; 1056 | } 1057 | } 1058 | saveLastMotion(ev); 1059 | break; 1060 | } 1061 | 1062 | case MotionEventCompat.ACTION_POINTER_UP: { 1063 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 1064 | clearMotionHistory(pointerId); 1065 | break; 1066 | } 1067 | 1068 | case MotionEvent.ACTION_UP: 1069 | case MotionEvent.ACTION_CANCEL: { 1070 | cancel(); 1071 | break; 1072 | } 1073 | } 1074 | 1075 | return mDragState == STATE_DRAGGING; 1076 | } 1077 | 1078 | /** 1079 | * Process a touch event received by the parent view. This method will dispatch callback events 1080 | * as needed before returning. The parent view's onTouchEvent implementation should call this. 1081 | * 1082 | * @param ev The touch event received by the parent view 1083 | */ 1084 | public void processTouchEvent(MotionEvent ev) { 1085 | final int action = MotionEventCompat.getActionMasked(ev); 1086 | final int actionIndex = MotionEventCompat.getActionIndex(ev); 1087 | 1088 | if (action == MotionEvent.ACTION_DOWN) { 1089 | // Reset things for a new event stream, just in case we didn't get 1090 | // the whole previous stream. 1091 | cancel(); 1092 | } 1093 | 1094 | if (mVelocityTracker == null) { 1095 | mVelocityTracker = VelocityTracker.obtain(); 1096 | } 1097 | mVelocityTracker.addMovement(ev); 1098 | 1099 | switch (action) { 1100 | case MotionEvent.ACTION_DOWN: { 1101 | final float x = ev.getX(); 1102 | final float y = ev.getY(); 1103 | final int pointerId = MotionEventCompat.getPointerId(ev, 0); 1104 | final View toCapture = findTopChildUnder((int) x, (int) y); 1105 | 1106 | saveInitialMotion(x, y, pointerId); 1107 | 1108 | // Since the parent is already directly processing this touch event, 1109 | // there is no reason to delay for a slop before dragging. 1110 | // Start immediately if possible. 1111 | tryCaptureViewForDrag(toCapture, pointerId); 1112 | 1113 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 1114 | if ((edgesTouched & mTrackingEdges) != 0) { 1115 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 1116 | } 1117 | break; 1118 | } 1119 | 1120 | case MotionEventCompat.ACTION_POINTER_DOWN: { 1121 | final int pointerId = MotionEventCompat.getPointerId(ev, actionIndex); 1122 | final float x = MotionEventCompat.getX(ev, actionIndex); 1123 | final float y = MotionEventCompat.getY(ev, actionIndex); 1124 | 1125 | saveInitialMotion(x, y, pointerId); 1126 | 1127 | // A ViewDragHelper can only manipulate one view at a time. 1128 | if (mDragState == STATE_IDLE) { 1129 | // If we're idle we can do anything! Treat it like a normal down event. 1130 | 1131 | final View toCapture = findTopChildUnder((int) x, (int) y); 1132 | tryCaptureViewForDrag(toCapture, pointerId); 1133 | 1134 | final int edgesTouched = mInitialEdgesTouched[pointerId]; 1135 | if ((edgesTouched & mTrackingEdges) != 0) { 1136 | mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); 1137 | } 1138 | } else if (isCapturedViewUnder((int) x, (int) y)) { 1139 | // We're still tracking a captured view. If the same view is under this 1140 | // point, we'll swap to controlling it with this pointer instead. 1141 | // (This will still work if we're "catching" a settling view.) 1142 | 1143 | tryCaptureViewForDrag(mCapturedView, pointerId); 1144 | } 1145 | break; 1146 | } 1147 | 1148 | case MotionEvent.ACTION_MOVE: { 1149 | if (mDragState == STATE_DRAGGING) { 1150 | final int index = MotionEventCompat.findPointerIndex(ev, mActivePointerId); 1151 | final float x = MotionEventCompat.getX(ev, index); 1152 | final float y = MotionEventCompat.getY(ev, index); 1153 | final int idx = (int) (x - mLastMotionX[mActivePointerId]); 1154 | final int idy = (int) (y - mLastMotionY[mActivePointerId]); 1155 | 1156 | dragTo(mCapturedView.getLeft() + idx, mCapturedView.getTop() + idy, idx, idy); 1157 | 1158 | saveLastMotion(ev); 1159 | } else { 1160 | // Check to see if any pointer is now over a draggable view. 1161 | final int pointerCount = MotionEventCompat.getPointerCount(ev); 1162 | for (int i = 0; i < pointerCount; i++) { 1163 | final int pointerId = MotionEventCompat.getPointerId(ev, i); 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 | mCapturedView.offsetLeftAndRight(clampedX - oldLeft); 1412 | } 1413 | if (dy != 0) { 1414 | clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy); 1415 | mCapturedView.offsetTopAndBottom(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 com.laowch.pulltoback.ViewDragHelper.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 | } -------------------------------------------------------------------------------- /app/src/main/java/com/laowch/pulltoback/sample/ListViewFragment.java: -------------------------------------------------------------------------------- 1 | package com.laowch.pulltoback.sample; 2 | 3 | import android.os.Bundle; 4 | import android.support.annotation.Nullable; 5 | import android.support.v4.app.Fragment; 6 | import android.view.LayoutInflater; 7 | import android.view.View; 8 | import android.view.ViewGroup; 9 | import android.widget.ArrayAdapter; 10 | import android.widget.ListView; 11 | 12 | import com.laowch.pulltoback.R; 13 | 14 | /** 15 | * Created by lao on 14/11/30. 16 | */ 17 | public class ListViewFragment extends Fragment { 18 | 19 | @Override 20 | public void onCreate(Bundle savedInstanceState) { 21 | super.onCreate(savedInstanceState); 22 | getActivity().setTitle("A Simple ListView"); 23 | } 24 | 25 | @Override 26 | public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 27 | View layout = inflater.inflate(R.layout.fragment_listview, container, false); 28 | 29 | ListView listView = (ListView) layout.findViewById(R.id.list); 30 | listView.setAdapter(new ArrayAdapter