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