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