ItemTouchHelper.java revision 1b3e9466b4c4d72f28bb4448672ef8bab19b6f3e
1/* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.support.v7.widget.helper; 18 19import android.content.res.Resources; 20import android.graphics.Canvas; 21import android.graphics.Rect; 22import android.os.Build; 23import android.support.annotation.Nullable; 24import android.support.v4.animation.AnimatorCompatHelper; 25import android.support.v4.animation.AnimatorListenerCompat; 26import android.support.v4.animation.AnimatorUpdateListenerCompat; 27import android.support.v4.animation.ValueAnimatorCompat; 28import android.support.v4.view.GestureDetectorCompat; 29import android.support.v4.view.MotionEventCompat; 30import android.support.v4.view.VelocityTrackerCompat; 31import android.support.v4.view.ViewCompat; 32import android.support.v7.recyclerview.R; 33import android.support.v7.widget.LinearLayoutManager; 34import android.support.v7.widget.RecyclerView; 35import android.support.v7.widget.RecyclerView.OnItemTouchListener; 36import android.support.v7.widget.RecyclerView.ViewHolder; 37import android.util.Log; 38import android.view.GestureDetector; 39import android.view.HapticFeedbackConstants; 40import android.view.MotionEvent; 41import android.view.VelocityTracker; 42import android.view.View; 43import android.view.ViewConfiguration; 44import android.view.ViewParent; 45import android.view.animation.Interpolator; 46 47import java.util.ArrayList; 48import java.util.List; 49 50/** 51 * This is a utility class to add swipe to dismiss and drag & drop support to RecyclerView. 52 * <p> 53 * It works with a RecyclerView and a Callback class, which configures what type of interactions 54 * are enabled and also receives events when user performs these actions. 55 * <p> 56 * Depending on which functionality you support, you should override 57 * {@link Callback#onMove(RecyclerView, ViewHolder, ViewHolder)} and / or 58 * {@link Callback#onSwiped(ViewHolder, int)}. 59 * <p> 60 * This class is designed to work with any LayoutManager but for certain situations, it can be 61 * optimized for your custom LayoutManager by extending methods in the 62 * {@link ItemTouchHelper.Callback} class or implementing {@link ItemTouchHelper.ViewDropHandler} 63 * interface in your LayoutManager. 64 * <p> 65 * By default, ItemTouchHelper moves the items' translateX/Y properties to reposition them. On 66 * platforms older than Honeycomb, ItemTouchHelper uses canvas translations and View's visibility 67 * property to move items in response to touch events. You can customize these behaviors by 68 * overriding {@link Callback#onChildDraw(Canvas, RecyclerView, ViewHolder, float, float, int, 69 * boolean)} 70 * or {@link Callback#onChildDrawOver(Canvas, RecyclerView, ViewHolder, float, float, int, 71 * boolean)}. 72 * <p/> 73 * Most of the time, you only need to override <code>onChildDraw</code> but due to limitations of 74 * platform prior to Honeycomb, you may need to implement <code>onChildDrawOver</code> as well. 75 */ 76public class ItemTouchHelper extends RecyclerView.ItemDecoration 77 implements RecyclerView.OnChildAttachStateChangeListener { 78 79 /** 80 * Up direction, used for swipe & drag control. 81 */ 82 public static final int UP = 1; 83 84 /** 85 * Down direction, used for swipe & drag control. 86 */ 87 public static final int DOWN = 1 << 1; 88 89 /** 90 * Left direction, used for swipe & drag control. 91 */ 92 public static final int LEFT = 1 << 2; 93 94 /** 95 * Right direction, used for swipe & drag control. 96 */ 97 public static final int RIGHT = 1 << 3; 98 99 // If you change these relative direction values, update Callback#convertToAbsoluteDirection, 100 // Callback#convertToRelativeDirection. 101 /** 102 * Horizontal start direction. Resolved to LEFT or RIGHT depending on RecyclerView's layout 103 * direction. Used for swipe & drag control. 104 */ 105 public static final int START = LEFT << 2; 106 107 /** 108 * Horizontal end direction. Resolved to LEFT or RIGHT depending on RecyclerView's layout 109 * direction. Used for swipe & drag control. 110 */ 111 public static final int END = RIGHT << 2; 112 113 /** 114 * ItemTouchHelper is in idle state. At this state, either there is no related motion event by 115 * the user or latest motion events have not yet triggered a swipe or drag. 116 */ 117 public static final int ACTION_STATE_IDLE = 0; 118 119 /** 120 * A View is currently being swiped. 121 */ 122 public static final int ACTION_STATE_SWIPE = 1; 123 124 /** 125 * A View is currently being dragged. 126 */ 127 public static final int ACTION_STATE_DRAG = 2; 128 129 /** 130 * Animation type for views which are swiped successfully. 131 */ 132 public static final int ANIMATION_TYPE_SWIPE_SUCCESS = 1 << 1; 133 134 /** 135 * Animation type for views which are not completely swiped thus will animate back to their 136 * original position. 137 */ 138 public static final int ANIMATION_TYPE_SWIPE_CANCEL = 1 << 2; 139 140 /** 141 * Animation type for views that were dragged and now will animate to their final position. 142 */ 143 public static final int ANIMATION_TYPE_DRAG = 1 << 3; 144 145 private static final String TAG = "ItemTouchHelper"; 146 147 private static final boolean DEBUG = false; 148 149 private static final int ACTIVE_POINTER_ID_NONE = -1; 150 151 private static final int DIRECTION_FLAG_COUNT = 8; 152 153 private static final int ACTION_MODE_IDLE_MASK = (1 << DIRECTION_FLAG_COUNT) - 1; 154 155 private static final int ACTION_MODE_SWIPE_MASK = ACTION_MODE_IDLE_MASK << DIRECTION_FLAG_COUNT; 156 157 private static final int ACTION_MODE_DRAG_MASK = ACTION_MODE_SWIPE_MASK << DIRECTION_FLAG_COUNT; 158 159 /** 160 * The unit we are using to track velocity 161 */ 162 private static final int PIXELS_PER_SECOND = 1000; 163 164 /** 165 * Views, whose state should be cleared after they are detached from RecyclerView. 166 * This is necessary after swipe dismissing an item. We wait until animator finishes its job 167 * to clean these views. 168 */ 169 final List<View> mPendingCleanup = new ArrayList<View>(); 170 171 /** 172 * Re-use array to calculate dx dy for a ViewHolder 173 */ 174 private final float[] mTmpPosition = new float[2]; 175 176 /** 177 * Currently selected view holder 178 */ 179 ViewHolder mSelected = null; 180 181 /** 182 * The reference coordinates for the action start. For drag & drop, this is the time long 183 * press is completed vs for swipe, this is the initial touch point. 184 */ 185 float mInitialTouchX; 186 187 float mInitialTouchY; 188 189 /** 190 * Set when ItemTouchHelper is assigned to a RecyclerView. 191 */ 192 float mSwipeEscapeVelocity; 193 194 /** 195 * Set when ItemTouchHelper is assigned to a RecyclerView. 196 */ 197 float mMaxSwipeVelocity; 198 199 /** 200 * The diff between the last event and initial touch. 201 */ 202 float mDx; 203 204 float mDy; 205 206 /** 207 * The coordinates of the selected view at the time it is selected. We record these values 208 * when action starts so that we can consistently position it even if LayoutManager moves the 209 * View. 210 */ 211 float mSelectedStartX; 212 213 float mSelectedStartY; 214 215 /** 216 * The pointer we are tracking. 217 */ 218 int mActivePointerId = ACTIVE_POINTER_ID_NONE; 219 220 /** 221 * Developer callback which controls the behavior of ItemTouchHelper. 222 */ 223 Callback mCallback; 224 225 /** 226 * Current mode. 227 */ 228 int mActionState = ACTION_STATE_IDLE; 229 230 /** 231 * The direction flags obtained from unmasking 232 * {@link Callback#getAbsoluteMovementFlags(RecyclerView, ViewHolder)} for the current 233 * action state. 234 */ 235 int mSelectedFlags; 236 237 /** 238 * When a View is dragged or swiped and needs to go back to where it was, we create a Recover 239 * Animation and animate it to its location using this custom Animator, instead of using 240 * framework Animators. 241 * Using framework animators has the side effect of clashing with ItemAnimator, creating 242 * jumpy UIs. 243 */ 244 List<RecoverAnimation> mRecoverAnimations = new ArrayList<RecoverAnimation>(); 245 246 private int mSlop; 247 248 private RecyclerView mRecyclerView; 249 250 /** 251 * When user drags a view to the edge, we start scrolling the LayoutManager as long as View 252 * is partially out of bounds. 253 */ 254 private final Runnable mScrollRunnable = new Runnable() { 255 @Override 256 public void run() { 257 if (mSelected != null && scrollIfNecessary()) { 258 if (mSelected != null) { //it might be lost during scrolling 259 moveIfNecessary(mSelected); 260 } 261 mRecyclerView.removeCallbacks(mScrollRunnable); 262 ViewCompat.postOnAnimation(mRecyclerView, this); 263 } 264 } 265 }; 266 267 /** 268 * Used for detecting fling swipe 269 */ 270 private VelocityTracker mVelocityTracker; 271 272 //re-used list for selecting a swap target 273 private List<ViewHolder> mSwapTargets; 274 275 //re used for for sorting swap targets 276 private List<Integer> mDistances; 277 278 /** 279 * If drag & drop is supported, we use child drawing order to bring them to front. 280 */ 281 private RecyclerView.ChildDrawingOrderCallback mChildDrawingOrderCallback = null; 282 283 /** 284 * This keeps a reference to the child dragged by the user. Even after user stops dragging, 285 * until view reaches its final position (end of recover animation), we keep a reference so 286 * that it can be drawn above other children. 287 */ 288 private View mOverdrawChild = null; 289 290 /** 291 * We cache the position of the overdraw child to avoid recalculating it each time child 292 * position callback is called. This value is invalidated whenever a child is attached or 293 * detached. 294 */ 295 private int mOverdrawChildPosition = -1; 296 297 /** 298 * Used to detect long press. 299 */ 300 private GestureDetectorCompat mGestureDetector; 301 302 private final OnItemTouchListener mOnItemTouchListener 303 = new OnItemTouchListener() { 304 @Override 305 public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent event) { 306 mGestureDetector.onTouchEvent(event); 307 if (DEBUG) { 308 Log.d(TAG, "intercept: x:" + event.getX() + ",y:" + event.getY() + ", " + event); 309 } 310 final int action = MotionEventCompat.getActionMasked(event); 311 if (action == MotionEvent.ACTION_DOWN) { 312 mActivePointerId = event.getPointerId(0); 313 mInitialTouchX = event.getX(); 314 mInitialTouchY = event.getY(); 315 obtainVelocityTracker(); 316 if (mSelected == null) { 317 final RecoverAnimation animation = findAnimation(event); 318 if (animation != null) { 319 mInitialTouchX -= animation.mX; 320 mInitialTouchY -= animation.mY; 321 endRecoverAnimation(animation.mViewHolder, true); 322 if (mPendingCleanup.remove(animation.mViewHolder.itemView)) { 323 mCallback.clearView(mRecyclerView, animation.mViewHolder); 324 } 325 select(animation.mViewHolder, animation.mActionState); 326 updateDxDy(event, mSelectedFlags, 0); 327 } 328 } 329 } else if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 330 mActivePointerId = ACTIVE_POINTER_ID_NONE; 331 select(null, ACTION_STATE_IDLE); 332 } else if (mActivePointerId != ACTIVE_POINTER_ID_NONE) { 333 // in a non scroll orientation, if distance change is above threshold, we 334 // can select the item 335 final int index = event.findPointerIndex(mActivePointerId); 336 if (DEBUG) { 337 Log.d(TAG, "pointer index " + index); 338 } 339 if (index >= 0) { 340 checkSelectForSwipe(action, event, index); 341 } 342 } 343 if (mVelocityTracker != null) { 344 mVelocityTracker.addMovement(event); 345 } 346 return mSelected != null; 347 } 348 349 @Override 350 public void onTouchEvent(RecyclerView recyclerView, MotionEvent event) { 351 mGestureDetector.onTouchEvent(event); 352 if (DEBUG) { 353 Log.d(TAG, 354 "on touch: x:" + mInitialTouchX + ",y:" + mInitialTouchY + ", :" + event); 355 } 356 if (mVelocityTracker != null) { 357 mVelocityTracker.addMovement(event); 358 } 359 if (mActivePointerId == ACTIVE_POINTER_ID_NONE) { 360 return; 361 } 362 final int action = MotionEventCompat.getActionMasked(event); 363 final int activePointerIndex = event.findPointerIndex(mActivePointerId); 364 if (activePointerIndex >= 0) { 365 checkSelectForSwipe(action, event, activePointerIndex); 366 } 367 ViewHolder viewHolder = mSelected; 368 if (viewHolder == null) { 369 return; 370 } 371 switch (action) { 372 case MotionEvent.ACTION_MOVE: { 373 // Find the index of the active pointer and fetch its position 374 if (activePointerIndex >= 0) { 375 updateDxDy(event, mSelectedFlags, activePointerIndex); 376 moveIfNecessary(viewHolder); 377 mRecyclerView.removeCallbacks(mScrollRunnable); 378 mScrollRunnable.run(); 379 mRecyclerView.invalidate(); 380 } 381 break; 382 } 383 case MotionEvent.ACTION_CANCEL: 384 if (mVelocityTracker != null) { 385 mVelocityTracker.clear(); 386 } 387 // fall through 388 case MotionEvent.ACTION_UP: 389 select(null, ACTION_STATE_IDLE); 390 mActivePointerId = ACTIVE_POINTER_ID_NONE; 391 break; 392 case MotionEvent.ACTION_POINTER_UP: { 393 final int pointerIndex = MotionEventCompat.getActionIndex(event); 394 final int pointerId = event.getPointerId(pointerIndex); 395 if (pointerId == mActivePointerId) { 396 // This was our active pointer going up. Choose a new 397 // active pointer and adjust accordingly. 398 final int newPointerIndex = pointerIndex == 0 ? 1 : 0; 399 mActivePointerId = event.getPointerId(newPointerIndex); 400 updateDxDy(event, mSelectedFlags, pointerIndex); 401 } 402 break; 403 } 404 } 405 } 406 407 @Override 408 public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { 409 if (!disallowIntercept) { 410 return; 411 } 412 select(null, ACTION_STATE_IDLE); 413 } 414 }; 415 416 /** 417 * Temporary rect instance that is used when we need to lookup Item decorations. 418 */ 419 private Rect mTmpRect; 420 421 /** 422 * When user started to drag scroll. Reset when we don't scroll 423 */ 424 private long mDragScrollStartTimeInMs; 425 426 /** 427 * Creates an ItemTouchHelper that will work with the given Callback. 428 * <p> 429 * You can attach ItemTouchHelper to a RecyclerView via 430 * {@link #attachToRecyclerView(RecyclerView)}. Upon attaching, it will add an item decoration, 431 * an onItemTouchListener and a Child attach / detach listener to the RecyclerView. 432 * 433 * @param callback The Callback which controls the behavior of this touch helper. 434 */ 435 public ItemTouchHelper(Callback callback) { 436 mCallback = callback; 437 } 438 439 private static boolean hitTest(View child, float x, float y, float left, float top) { 440 return x >= left && 441 x <= left + child.getWidth() && 442 y >= top && 443 y <= top + child.getHeight(); 444 } 445 446 /** 447 * Attaches the ItemTouchHelper to the provided RecyclerView. If TouchHelper is already 448 * attached to a RecyclerView, it will first detach from the previous one. You can call this 449 * method with {@code null} to detach it from the current RecyclerView. 450 * 451 * @param recyclerView The RecyclerView instance to which you want to add this helper or 452 * {@code null} if you want to remove ItemTouchHelper from the current 453 * RecyclerView. 454 */ 455 public void attachToRecyclerView(@Nullable RecyclerView recyclerView) { 456 if (mRecyclerView == recyclerView) { 457 return; // nothing to do 458 } 459 if (mRecyclerView != null) { 460 destroyCallbacks(); 461 } 462 mRecyclerView = recyclerView; 463 if (mRecyclerView != null) { 464 final Resources resources = recyclerView.getResources(); 465 mSwipeEscapeVelocity = resources 466 .getDimension(R.dimen.item_touch_helper_swipe_escape_velocity); 467 mMaxSwipeVelocity = resources 468 .getDimension(R.dimen.item_touch_helper_swipe_escape_max_velocity); 469 setupCallbacks(); 470 } 471 } 472 473 private void setupCallbacks() { 474 ViewConfiguration vc = ViewConfiguration.get(mRecyclerView.getContext()); 475 mSlop = vc.getScaledTouchSlop(); 476 mRecyclerView.addItemDecoration(this); 477 mRecyclerView.addOnItemTouchListener(mOnItemTouchListener); 478 mRecyclerView.addOnChildAttachStateChangeListener(this); 479 initGestureDetector(); 480 } 481 482 private void destroyCallbacks() { 483 mRecyclerView.removeItemDecoration(this); 484 mRecyclerView.removeOnItemTouchListener(mOnItemTouchListener); 485 mRecyclerView.removeOnChildAttachStateChangeListener(this); 486 // clean all attached 487 final int recoverAnimSize = mRecoverAnimations.size(); 488 for (int i = recoverAnimSize - 1; i >= 0; i--) { 489 final RecoverAnimation recoverAnimation = mRecoverAnimations.get(0); 490 mCallback.clearView(mRecyclerView, recoverAnimation.mViewHolder); 491 } 492 mRecoverAnimations.clear(); 493 mOverdrawChild = null; 494 mOverdrawChildPosition = -1; 495 releaseVelocityTracker(); 496 } 497 498 private void initGestureDetector() { 499 if (mGestureDetector != null) { 500 return; 501 } 502 mGestureDetector = new GestureDetectorCompat(mRecyclerView.getContext(), 503 new ItemTouchHelperGestureListener()); 504 } 505 506 private void getSelectedDxDy(float[] outPosition) { 507 if ((mSelectedFlags & (LEFT | RIGHT)) != 0) { 508 outPosition[0] = mSelectedStartX + mDx - mSelected.itemView.getLeft(); 509 } else { 510 outPosition[0] = ViewCompat.getTranslationX(mSelected.itemView); 511 } 512 if ((mSelectedFlags & (UP | DOWN)) != 0) { 513 outPosition[1] = mSelectedStartY + mDy - mSelected.itemView.getTop(); 514 } else { 515 outPosition[1] = ViewCompat.getTranslationY(mSelected.itemView); 516 } 517 } 518 519 @Override 520 public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { 521 float dx = 0, dy = 0; 522 if (mSelected != null) { 523 getSelectedDxDy(mTmpPosition); 524 dx = mTmpPosition[0]; 525 dy = mTmpPosition[1]; 526 } 527 mCallback.onDrawOver(c, parent, mSelected, 528 mRecoverAnimations, mActionState, dx, dy); 529 } 530 531 @Override 532 public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { 533 // we don't know if RV changed something so we should invalidate this index. 534 mOverdrawChildPosition = -1; 535 float dx = 0, dy = 0; 536 if (mSelected != null) { 537 getSelectedDxDy(mTmpPosition); 538 dx = mTmpPosition[0]; 539 dy = mTmpPosition[1]; 540 } 541 mCallback.onDraw(c, parent, mSelected, 542 mRecoverAnimations, mActionState, dx, dy); 543 } 544 545 /** 546 * Starts dragging or swiping the given View. Call with null if you want to clear it. 547 * 548 * @param selected The ViewHolder to drag or swipe. Can be null if you want to cancel the 549 * current action 550 * @param actionState The type of action 551 */ 552 private void select(ViewHolder selected, int actionState) { 553 if (selected == mSelected && actionState == mActionState) { 554 return; 555 } 556 mDragScrollStartTimeInMs = Long.MIN_VALUE; 557 final int prevActionState = mActionState; 558 // prevent duplicate animations 559 endRecoverAnimation(selected, true); 560 mActionState = actionState; 561 if (actionState == ACTION_STATE_DRAG) { 562 // we remove after animation is complete. this means we only elevate the last drag 563 // child but that should perform good enough as it is very hard to start dragging a 564 // new child before the previous one settles. 565 mOverdrawChild = selected.itemView; 566 addChildDrawingOrderCallback(); 567 } 568 int actionStateMask = (1 << (DIRECTION_FLAG_COUNT + DIRECTION_FLAG_COUNT * actionState)) 569 - 1; 570 boolean preventLayout = false; 571 572 if (mSelected != null) { 573 final ViewHolder prevSelected = mSelected; 574 if (prevSelected.itemView.getParent() != null) { 575 final int swipeDir = prevActionState == ACTION_STATE_DRAG ? 0 576 : swipeIfNecessary(prevSelected); 577 releaseVelocityTracker(); 578 // find where we should animate to 579 final float targetTranslateX, targetTranslateY; 580 int animationType; 581 switch (swipeDir) { 582 case LEFT: 583 case RIGHT: 584 case START: 585 case END: 586 targetTranslateY = 0; 587 targetTranslateX = Math.signum(mDx) * mRecyclerView.getWidth(); 588 break; 589 case UP: 590 case DOWN: 591 targetTranslateX = 0; 592 targetTranslateY = Math.signum(mDy) * mRecyclerView.getHeight(); 593 break; 594 default: 595 targetTranslateX = 0; 596 targetTranslateY = 0; 597 } 598 if (prevActionState == ACTION_STATE_DRAG) { 599 animationType = ANIMATION_TYPE_DRAG; 600 } else if (swipeDir > 0) { 601 animationType = ANIMATION_TYPE_SWIPE_SUCCESS; 602 } else { 603 animationType = ANIMATION_TYPE_SWIPE_CANCEL; 604 } 605 getSelectedDxDy(mTmpPosition); 606 final float currentTranslateX = mTmpPosition[0]; 607 final float currentTranslateY = mTmpPosition[1]; 608 final RecoverAnimation rv = new RecoverAnimation(prevSelected, animationType, 609 prevActionState, currentTranslateX, currentTranslateY, 610 targetTranslateX, targetTranslateY) { 611 @Override 612 public void onAnimationEnd(ValueAnimatorCompat animation) { 613 super.onAnimationEnd(animation); 614 if (this.mOverridden) { 615 return; 616 } 617 if (swipeDir <= 0) { 618 // this is a drag or failed swipe. recover immediately 619 mCallback.clearView(mRecyclerView, prevSelected); 620 // full cleanup will happen on onDrawOver 621 } else { 622 // wait until remove animation is complete. 623 mPendingCleanup.add(prevSelected.itemView); 624 mIsPendingCleanup = true; 625 if (swipeDir > 0) { 626 // Animation might be ended by other animators during a layout. 627 // We defer callback to avoid editing adapter during a layout. 628 postDispatchSwipe(this, swipeDir); 629 } 630 } 631 // removed from the list after it is drawn for the last time 632 if (mOverdrawChild == prevSelected.itemView) { 633 removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView); 634 } 635 } 636 }; 637 final long duration = mCallback.getAnimationDuration(mRecyclerView, animationType, 638 targetTranslateX - currentTranslateX, targetTranslateY - currentTranslateY); 639 rv.setDuration(duration); 640 mRecoverAnimations.add(rv); 641 rv.start(); 642 preventLayout = true; 643 } else { 644 removeChildDrawingOrderCallbackIfNecessary(prevSelected.itemView); 645 mCallback.clearView(mRecyclerView, prevSelected); 646 } 647 mSelected = null; 648 } 649 if (selected != null) { 650 mSelectedFlags = 651 (mCallback.getAbsoluteMovementFlags(mRecyclerView, selected) & actionStateMask) 652 >> (mActionState * DIRECTION_FLAG_COUNT); 653 mSelectedStartX = selected.itemView.getLeft(); 654 mSelectedStartY = selected.itemView.getTop(); 655 mSelected = selected; 656 657 if (actionState == ACTION_STATE_DRAG) { 658 mSelected.itemView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS); 659 } 660 } 661 final ViewParent rvParent = mRecyclerView.getParent(); 662 if (rvParent != null) { 663 rvParent.requestDisallowInterceptTouchEvent(mSelected != null); 664 } 665 if (!preventLayout) { 666 mRecyclerView.getLayoutManager().requestSimpleAnimationsInNextLayout(); 667 } 668 mCallback.onSelectedChanged(mSelected, mActionState); 669 mRecyclerView.invalidate(); 670 } 671 672 private void postDispatchSwipe(final RecoverAnimation anim, final int swipeDir) { 673 // wait until animations are complete. 674 mRecyclerView.post(new Runnable() { 675 @Override 676 public void run() { 677 if (mRecyclerView != null && mRecyclerView.isAttachedToWindow() && 678 !anim.mOverridden && 679 anim.mViewHolder.getAdapterPosition() != RecyclerView.NO_POSITION) { 680 final RecyclerView.ItemAnimator animator = mRecyclerView.getItemAnimator(); 681 // if animator is running or we have other active recover animations, we try 682 // not to call onSwiped because DefaultItemAnimator is not good at merging 683 // animations. Instead, we wait and batch. 684 if ((animator == null || !animator.isRunning(null)) 685 && !hasRunningRecoverAnim()) { 686 mCallback.onSwiped(anim.mViewHolder, swipeDir); 687 } else { 688 mRecyclerView.post(this); 689 } 690 } 691 } 692 }); 693 } 694 695 private boolean hasRunningRecoverAnim() { 696 final int size = mRecoverAnimations.size(); 697 for (int i = 0; i < size; i++) { 698 if (!mRecoverAnimations.get(i).mEnded) { 699 return true; 700 } 701 } 702 return false; 703 } 704 705 /** 706 * If user drags the view to the edge, trigger a scroll if necessary. 707 */ 708 private boolean scrollIfNecessary() { 709 if (mSelected == null) { 710 mDragScrollStartTimeInMs = Long.MIN_VALUE; 711 return false; 712 } 713 final long now = System.currentTimeMillis(); 714 final long scrollDuration = mDragScrollStartTimeInMs 715 == Long.MIN_VALUE ? 0 : now - mDragScrollStartTimeInMs; 716 RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager(); 717 if (mTmpRect == null) { 718 mTmpRect = new Rect(); 719 } 720 int scrollX = 0; 721 int scrollY = 0; 722 lm.calculateItemDecorationsForChild(mSelected.itemView, mTmpRect); 723 if (lm.canScrollHorizontally()) { 724 int curX = (int) (mSelectedStartX + mDx); 725 final int leftDiff = curX - mTmpRect.left - mRecyclerView.getPaddingLeft(); 726 if (mDx < 0 && leftDiff < 0) { 727 scrollX = leftDiff; 728 } else if (mDx > 0) { 729 final int rightDiff = 730 curX + mSelected.itemView.getWidth() + mTmpRect.right 731 - (mRecyclerView.getWidth() - mRecyclerView.getPaddingRight()); 732 if (rightDiff > 0) { 733 scrollX = rightDiff; 734 } 735 } 736 } 737 if (lm.canScrollVertically()) { 738 int curY = (int) (mSelectedStartY + mDy); 739 final int topDiff = curY - mTmpRect.top - mRecyclerView.getPaddingTop(); 740 if (mDy < 0 && topDiff < 0) { 741 scrollY = topDiff; 742 } else if (mDy > 0) { 743 final int bottomDiff = curY + mSelected.itemView.getHeight() + mTmpRect.bottom - 744 (mRecyclerView.getHeight() - mRecyclerView.getPaddingBottom()); 745 if (bottomDiff > 0) { 746 scrollY = bottomDiff; 747 } 748 } 749 } 750 if (scrollX != 0) { 751 scrollX = mCallback.interpolateOutOfBoundsScroll(mRecyclerView, 752 mSelected.itemView.getWidth(), scrollX, 753 mRecyclerView.getWidth(), scrollDuration); 754 } 755 if (scrollY != 0) { 756 scrollY = mCallback.interpolateOutOfBoundsScroll(mRecyclerView, 757 mSelected.itemView.getHeight(), scrollY, 758 mRecyclerView.getHeight(), scrollDuration); 759 } 760 if (scrollX != 0 || scrollY != 0) { 761 if (mDragScrollStartTimeInMs == Long.MIN_VALUE) { 762 mDragScrollStartTimeInMs = now; 763 } 764 mRecyclerView.scrollBy(scrollX, scrollY); 765 return true; 766 } 767 mDragScrollStartTimeInMs = Long.MIN_VALUE; 768 return false; 769 } 770 771 private List<ViewHolder> findSwapTargets(ViewHolder viewHolder) { 772 if (mSwapTargets == null) { 773 mSwapTargets = new ArrayList<ViewHolder>(); 774 mDistances = new ArrayList<Integer>(); 775 } else { 776 mSwapTargets.clear(); 777 mDistances.clear(); 778 } 779 final int margin = mCallback.getBoundingBoxMargin(); 780 final int left = Math.round(mSelectedStartX + mDx) - margin; 781 final int top = Math.round(mSelectedStartY + mDy) - margin; 782 final int right = left + viewHolder.itemView.getWidth() + 2 * margin; 783 final int bottom = top + viewHolder.itemView.getHeight() + 2 * margin; 784 final int centerX = (left + right) / 2; 785 final int centerY = (top + bottom) / 2; 786 final RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager(); 787 final int childCount = lm.getChildCount(); 788 for (int i = 0; i < childCount; i++) { 789 View other = lm.getChildAt(i); 790 if (other == viewHolder.itemView) { 791 continue;//myself! 792 } 793 if (other.getBottom() < top || other.getTop() > bottom 794 || other.getRight() < left || other.getLeft() > right) { 795 continue; 796 } 797 final ViewHolder otherVh = mRecyclerView.getChildViewHolder(other); 798 if (mCallback.canDropOver(mRecyclerView, mSelected, otherVh)) { 799 // find the index to add 800 final int dx = Math.abs(centerX - (other.getLeft() + other.getRight()) / 2); 801 final int dy = Math.abs(centerY - (other.getTop() + other.getBottom()) / 2); 802 final int dist = dx * dx + dy * dy; 803 804 int pos = 0; 805 final int cnt = mSwapTargets.size(); 806 for (int j = 0; j < cnt; j++) { 807 if (dist > mDistances.get(j)) { 808 pos++; 809 } else { 810 break; 811 } 812 } 813 mSwapTargets.add(pos, otherVh); 814 mDistances.add(pos, dist); 815 } 816 } 817 return mSwapTargets; 818 } 819 820 /** 821 * Checks if we should swap w/ another view holder. 822 */ 823 private void moveIfNecessary(ViewHolder viewHolder) { 824 if (mRecyclerView.isLayoutRequested()) { 825 return; 826 } 827 if (mActionState != ACTION_STATE_DRAG) { 828 return; 829 } 830 831 final float threshold = mCallback.getMoveThreshold(viewHolder); 832 final int x = (int) (mSelectedStartX + mDx); 833 final int y = (int) (mSelectedStartY + mDy); 834 if (Math.abs(y - viewHolder.itemView.getTop()) < viewHolder.itemView.getHeight() * threshold 835 && Math.abs(x - viewHolder.itemView.getLeft()) 836 < viewHolder.itemView.getWidth() * threshold) { 837 return; 838 } 839 List<ViewHolder> swapTargets = findSwapTargets(viewHolder); 840 if (swapTargets.size() == 0) { 841 return; 842 } 843 // may swap. 844 ViewHolder target = mCallback.chooseDropTarget(viewHolder, swapTargets, x, y); 845 if (target == null) { 846 mSwapTargets.clear(); 847 mDistances.clear(); 848 return; 849 } 850 final int toPosition = target.getAdapterPosition(); 851 final int fromPosition = viewHolder.getAdapterPosition(); 852 if (mCallback.onMove(mRecyclerView, viewHolder, target)) { 853 // keep target visible 854 mCallback.onMoved(mRecyclerView, viewHolder, fromPosition, 855 target, toPosition, x, y); 856 } 857 } 858 859 @Override 860 public void onChildViewAttachedToWindow(View view) { 861 } 862 863 @Override 864 public void onChildViewDetachedFromWindow(View view) { 865 removeChildDrawingOrderCallbackIfNecessary(view); 866 final ViewHolder holder = mRecyclerView.getChildViewHolder(view); 867 if (holder == null) { 868 return; 869 } 870 if (mSelected != null && holder == mSelected) { 871 select(null, ACTION_STATE_IDLE); 872 } else { 873 endRecoverAnimation(holder, false); // this may push it into pending cleanup list. 874 if (mPendingCleanup.remove(holder.itemView)) { 875 mCallback.clearView(mRecyclerView, holder); 876 } 877 } 878 } 879 880 /** 881 * Returns the animation type or 0 if cannot be found. 882 */ 883 private int endRecoverAnimation(ViewHolder viewHolder, boolean override) { 884 final int recoverAnimSize = mRecoverAnimations.size(); 885 for (int i = recoverAnimSize - 1; i >= 0; i--) { 886 final RecoverAnimation anim = mRecoverAnimations.get(i); 887 if (anim.mViewHolder == viewHolder) { 888 anim.mOverridden |= override; 889 if (!anim.mEnded) { 890 anim.cancel(); 891 } 892 mRecoverAnimations.remove(i); 893 return anim.mAnimationType; 894 } 895 } 896 return 0; 897 } 898 899 @Override 900 public void getItemOffsets(Rect outRect, View view, RecyclerView parent, 901 RecyclerView.State state) { 902 outRect.setEmpty(); 903 } 904 905 private void obtainVelocityTracker() { 906 if (mVelocityTracker != null) { 907 mVelocityTracker.recycle(); 908 } 909 mVelocityTracker = VelocityTracker.obtain(); 910 } 911 912 private void releaseVelocityTracker() { 913 if (mVelocityTracker != null) { 914 mVelocityTracker.recycle(); 915 mVelocityTracker = null; 916 } 917 } 918 919 private ViewHolder findSwipedView(MotionEvent motionEvent) { 920 final RecyclerView.LayoutManager lm = mRecyclerView.getLayoutManager(); 921 if (mActivePointerId == ACTIVE_POINTER_ID_NONE) { 922 return null; 923 } 924 final int pointerIndex = motionEvent.findPointerIndex(mActivePointerId); 925 final float dx = motionEvent.getX(pointerIndex) - mInitialTouchX; 926 final float dy = motionEvent.getY(pointerIndex) - mInitialTouchY; 927 final float absDx = Math.abs(dx); 928 final float absDy = Math.abs(dy); 929 930 if (absDx < mSlop && absDy < mSlop) { 931 return null; 932 } 933 if (absDx > absDy && lm.canScrollHorizontally()) { 934 return null; 935 } else if (absDy > absDx && lm.canScrollVertically()) { 936 return null; 937 } 938 View child = findChildView(motionEvent); 939 if (child == null) { 940 return null; 941 } 942 return mRecyclerView.getChildViewHolder(child); 943 } 944 945 /** 946 * Checks whether we should select a View for swiping. 947 */ 948 private boolean checkSelectForSwipe(int action, MotionEvent motionEvent, int pointerIndex) { 949 if (mSelected != null || action != MotionEvent.ACTION_MOVE 950 || mActionState == ACTION_STATE_DRAG || !mCallback.isItemViewSwipeEnabled()) { 951 return false; 952 } 953 if (mRecyclerView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING) { 954 return false; 955 } 956 final ViewHolder vh = findSwipedView(motionEvent); 957 if (vh == null) { 958 return false; 959 } 960 final int movementFlags = mCallback.getAbsoluteMovementFlags(mRecyclerView, vh); 961 962 final int swipeFlags = (movementFlags & ACTION_MODE_SWIPE_MASK) 963 >> (DIRECTION_FLAG_COUNT * ACTION_STATE_SWIPE); 964 965 if (swipeFlags == 0) { 966 return false; 967 } 968 969 // mDx and mDy are only set in allowed directions. We use custom x/y here instead of 970 // updateDxDy to avoid swiping if user moves more in the other direction 971 final float x = motionEvent.getX(pointerIndex); 972 final float y = motionEvent.getY(pointerIndex); 973 974 // Calculate the distance moved 975 final float dx = x - mInitialTouchX; 976 final float dy = y - mInitialTouchY; 977 // swipe target is chose w/o applying flags so it does not really check if swiping in that 978 // direction is allowed. This why here, we use mDx mDy to check slope value again. 979 final float absDx = Math.abs(dx); 980 final float absDy = Math.abs(dy); 981 982 if (absDx < mSlop && absDy < mSlop) { 983 return false; 984 } 985 if (absDx > absDy) { 986 if (dx < 0 && (swipeFlags & LEFT) == 0) { 987 return false; 988 } 989 if (dx > 0 && (swipeFlags & RIGHT) == 0) { 990 return false; 991 } 992 } else { 993 if (dy < 0 && (swipeFlags & UP) == 0) { 994 return false; 995 } 996 if (dy > 0 && (swipeFlags & DOWN) == 0) { 997 return false; 998 } 999 } 1000 mDx = mDy = 0f; 1001 mActivePointerId = motionEvent.getPointerId(0); 1002 select(vh, ACTION_STATE_SWIPE); 1003 return true; 1004 } 1005 1006 private View findChildView(MotionEvent event) { 1007 // first check elevated views, if none, then call RV 1008 final float x = event.getX(); 1009 final float y = event.getY(); 1010 if (mSelected != null) { 1011 final View selectedView = mSelected.itemView; 1012 if (hitTest(selectedView, x, y, mSelectedStartX + mDx, mSelectedStartY + mDy)) { 1013 return selectedView; 1014 } 1015 } 1016 for (int i = mRecoverAnimations.size() - 1; i >= 0; i--) { 1017 final RecoverAnimation anim = mRecoverAnimations.get(i); 1018 final View view = anim.mViewHolder.itemView; 1019 if (hitTest(view, x, y, anim.mX, anim.mY)) { 1020 return view; 1021 } 1022 } 1023 return mRecyclerView.findChildViewUnder(x, y); 1024 } 1025 1026 /** 1027 * Starts dragging the provided ViewHolder. By default, ItemTouchHelper starts a drag when a 1028 * View is long pressed. You can disable that behavior by overriding 1029 * {@link ItemTouchHelper.Callback#isLongPressDragEnabled()}. 1030 * <p> 1031 * For this method to work: 1032 * <ul> 1033 * <li>The provided ViewHolder must be a child of the RecyclerView to which this 1034 * ItemTouchHelper 1035 * is attached.</li> 1036 * <li>{@link ItemTouchHelper.Callback} must have dragging enabled.</li> 1037 * <li>There must be a previous touch event that was reported to the ItemTouchHelper 1038 * through RecyclerView's ItemTouchListener mechanism. As long as no other ItemTouchListener 1039 * grabs previous events, this should work as expected.</li> 1040 * </ul> 1041 * 1042 * For example, if you would like to let your user to be able to drag an Item by touching one 1043 * of its descendants, you may implement it as follows: 1044 * <pre> 1045 * viewHolder.dragButton.setOnTouchListener(new View.OnTouchListener() { 1046 * public boolean onTouch(View v, MotionEvent event) { 1047 * if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) { 1048 * mItemTouchHelper.startDrag(viewHolder); 1049 * } 1050 * return false; 1051 * } 1052 * }); 1053 * </pre> 1054 * <p> 1055 * 1056 * @param viewHolder The ViewHolder to start dragging. It must be a direct child of 1057 * RecyclerView. 1058 * @see ItemTouchHelper.Callback#isItemViewSwipeEnabled() 1059 */ 1060 public void startDrag(ViewHolder viewHolder) { 1061 if (!mCallback.hasDragFlag(mRecyclerView, viewHolder)) { 1062 Log.e(TAG, "Start drag has been called but swiping is not enabled"); 1063 return; 1064 } 1065 if (viewHolder.itemView.getParent() != mRecyclerView) { 1066 Log.e(TAG, "Start drag has been called with a view holder which is not a child of " 1067 + "the RecyclerView which is controlled by this ItemTouchHelper."); 1068 return; 1069 } 1070 obtainVelocityTracker(); 1071 mDx = mDy = 0f; 1072 select(viewHolder, ACTION_STATE_DRAG); 1073 } 1074 1075 /** 1076 * Starts swiping the provided ViewHolder. By default, ItemTouchHelper starts swiping a View 1077 * when user swipes their finger (or mouse pointer) over the View. You can disable this 1078 * behavior 1079 * by overriding {@link ItemTouchHelper.Callback} 1080 * <p> 1081 * For this method to work: 1082 * <ul> 1083 * <li>The provided ViewHolder must be a child of the RecyclerView to which this 1084 * ItemTouchHelper is attached.</li> 1085 * <li>{@link ItemTouchHelper.Callback} must have swiping enabled.</li> 1086 * <li>There must be a previous touch event that was reported to the ItemTouchHelper 1087 * through RecyclerView's ItemTouchListener mechanism. As long as no other ItemTouchListener 1088 * grabs previous events, this should work as expected.</li> 1089 * </ul> 1090 * 1091 * For example, if you would like to let your user to be able to swipe an Item by touching one 1092 * of its descendants, you may implement it as follows: 1093 * <pre> 1094 * viewHolder.dragButton.setOnTouchListener(new View.OnTouchListener() { 1095 * public boolean onTouch(View v, MotionEvent event) { 1096 * if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) { 1097 * mItemTouchHelper.startSwipe(viewHolder); 1098 * } 1099 * return false; 1100 * } 1101 * }); 1102 * </pre> 1103 * 1104 * @param viewHolder The ViewHolder to start swiping. It must be a direct child of 1105 * RecyclerView. 1106 */ 1107 public void startSwipe(ViewHolder viewHolder) { 1108 if (!mCallback.hasSwipeFlag(mRecyclerView, viewHolder)) { 1109 Log.e(TAG, "Start swipe has been called but dragging is not enabled"); 1110 return; 1111 } 1112 if (viewHolder.itemView.getParent() != mRecyclerView) { 1113 Log.e(TAG, "Start swipe has been called with a view holder which is not a child of " 1114 + "the RecyclerView controlled by this ItemTouchHelper."); 1115 return; 1116 } 1117 obtainVelocityTracker(); 1118 mDx = mDy = 0f; 1119 select(viewHolder, ACTION_STATE_SWIPE); 1120 } 1121 1122 private RecoverAnimation findAnimation(MotionEvent event) { 1123 if (mRecoverAnimations.isEmpty()) { 1124 return null; 1125 } 1126 View target = findChildView(event); 1127 for (int i = mRecoverAnimations.size() - 1; i >= 0; i--) { 1128 final RecoverAnimation anim = mRecoverAnimations.get(i); 1129 if (anim.mViewHolder.itemView == target) { 1130 return anim; 1131 } 1132 } 1133 return null; 1134 } 1135 1136 private void updateDxDy(MotionEvent ev, int directionFlags, int pointerIndex) { 1137 final float x = ev.getX(pointerIndex); 1138 final float y = ev.getY(pointerIndex); 1139 1140 // Calculate the distance moved 1141 mDx = x - mInitialTouchX; 1142 mDy = y - mInitialTouchY; 1143 if ((directionFlags & LEFT) == 0) { 1144 mDx = Math.max(0, mDx); 1145 } 1146 if ((directionFlags & RIGHT) == 0) { 1147 mDx = Math.min(0, mDx); 1148 } 1149 if ((directionFlags & UP) == 0) { 1150 mDy = Math.max(0, mDy); 1151 } 1152 if ((directionFlags & DOWN) == 0) { 1153 mDy = Math.min(0, mDy); 1154 } 1155 } 1156 1157 private int swipeIfNecessary(ViewHolder viewHolder) { 1158 if (mActionState == ACTION_STATE_DRAG) { 1159 return 0; 1160 } 1161 final int originalMovementFlags = mCallback.getMovementFlags(mRecyclerView, viewHolder); 1162 final int absoluteMovementFlags = mCallback.convertToAbsoluteDirection( 1163 originalMovementFlags, 1164 ViewCompat.getLayoutDirection(mRecyclerView)); 1165 final int flags = (absoluteMovementFlags 1166 & ACTION_MODE_SWIPE_MASK) >> (ACTION_STATE_SWIPE * DIRECTION_FLAG_COUNT); 1167 if (flags == 0) { 1168 return 0; 1169 } 1170 final int originalFlags = (originalMovementFlags 1171 & ACTION_MODE_SWIPE_MASK) >> (ACTION_STATE_SWIPE * DIRECTION_FLAG_COUNT); 1172 int swipeDir; 1173 if (Math.abs(mDx) > Math.abs(mDy)) { 1174 if ((swipeDir = checkHorizontalSwipe(viewHolder, flags)) > 0) { 1175 // if swipe dir is not in original flags, it should be the relative direction 1176 if ((originalFlags & swipeDir) == 0) { 1177 // convert to relative 1178 return Callback.convertToRelativeDirection(swipeDir, 1179 ViewCompat.getLayoutDirection(mRecyclerView)); 1180 } 1181 return swipeDir; 1182 } 1183 if ((swipeDir = checkVerticalSwipe(viewHolder, flags)) > 0) { 1184 return swipeDir; 1185 } 1186 } else { 1187 if ((swipeDir = checkVerticalSwipe(viewHolder, flags)) > 0) { 1188 return swipeDir; 1189 } 1190 if ((swipeDir = checkHorizontalSwipe(viewHolder, flags)) > 0) { 1191 // if swipe dir is not in original flags, it should be the relative direction 1192 if ((originalFlags & swipeDir) == 0) { 1193 // convert to relative 1194 return Callback.convertToRelativeDirection(swipeDir, 1195 ViewCompat.getLayoutDirection(mRecyclerView)); 1196 } 1197 return swipeDir; 1198 } 1199 } 1200 return 0; 1201 } 1202 1203 private int checkHorizontalSwipe(ViewHolder viewHolder, int flags) { 1204 if ((flags & (LEFT | RIGHT)) != 0) { 1205 final int dirFlag = mDx > 0 ? RIGHT : LEFT; 1206 if (mVelocityTracker != null && mActivePointerId > -1) { 1207 mVelocityTracker.computeCurrentVelocity(PIXELS_PER_SECOND, 1208 mCallback.getSwipeVelocityThreshold(mMaxSwipeVelocity)); 1209 final float xVelocity = VelocityTrackerCompat 1210 .getXVelocity(mVelocityTracker, mActivePointerId); 1211 final float yVelocity = VelocityTrackerCompat 1212 .getYVelocity(mVelocityTracker, mActivePointerId); 1213 final int velDirFlag = xVelocity > 0f ? RIGHT : LEFT; 1214 final float absXVelocity = Math.abs(xVelocity); 1215 if ((velDirFlag & flags) != 0 && dirFlag == velDirFlag && 1216 absXVelocity >= mCallback.getSwipeEscapeVelocity(mSwipeEscapeVelocity) && 1217 absXVelocity > Math.abs(yVelocity)) { 1218 return velDirFlag; 1219 } 1220 } 1221 1222 final float threshold = mRecyclerView.getWidth() * mCallback 1223 .getSwipeThreshold(viewHolder); 1224 1225 if ((flags & dirFlag) != 0 && Math.abs(mDx) > threshold) { 1226 return dirFlag; 1227 } 1228 } 1229 return 0; 1230 } 1231 1232 private int checkVerticalSwipe(ViewHolder viewHolder, int flags) { 1233 if ((flags & (UP | DOWN)) != 0) { 1234 final int dirFlag = mDy > 0 ? DOWN : UP; 1235 if (mVelocityTracker != null && mActivePointerId > -1) { 1236 mVelocityTracker.computeCurrentVelocity(PIXELS_PER_SECOND, 1237 mCallback.getSwipeVelocityThreshold(mMaxSwipeVelocity)); 1238 final float xVelocity = VelocityTrackerCompat 1239 .getXVelocity(mVelocityTracker, mActivePointerId); 1240 final float yVelocity = VelocityTrackerCompat 1241 .getYVelocity(mVelocityTracker, mActivePointerId); 1242 final int velDirFlag = yVelocity > 0f ? DOWN : UP; 1243 final float absYVelocity = Math.abs(yVelocity); 1244 if ((velDirFlag & flags) != 0 && velDirFlag == dirFlag && 1245 absYVelocity >= mCallback.getSwipeEscapeVelocity(mSwipeEscapeVelocity) && 1246 absYVelocity > Math.abs(xVelocity)) { 1247 return velDirFlag; 1248 } 1249 } 1250 1251 final float threshold = mRecyclerView.getHeight() * mCallback 1252 .getSwipeThreshold(viewHolder); 1253 if ((flags & dirFlag) != 0 && Math.abs(mDy) > threshold) { 1254 return dirFlag; 1255 } 1256 } 1257 return 0; 1258 } 1259 1260 private void addChildDrawingOrderCallback() { 1261 if (Build.VERSION.SDK_INT >= 21) { 1262 return;// we use elevation on Lollipop 1263 } 1264 if (mChildDrawingOrderCallback == null) { 1265 mChildDrawingOrderCallback = new RecyclerView.ChildDrawingOrderCallback() { 1266 @Override 1267 public int onGetChildDrawingOrder(int childCount, int i) { 1268 if (mOverdrawChild == null) { 1269 return i; 1270 } 1271 int childPosition = mOverdrawChildPosition; 1272 if (childPosition == -1) { 1273 childPosition = mRecyclerView.indexOfChild(mOverdrawChild); 1274 mOverdrawChildPosition = childPosition; 1275 } 1276 if (i == childCount - 1) { 1277 return childPosition; 1278 } 1279 return i < childPosition ? i : i + 1; 1280 } 1281 }; 1282 } 1283 mRecyclerView.setChildDrawingOrderCallback(mChildDrawingOrderCallback); 1284 } 1285 1286 private void removeChildDrawingOrderCallbackIfNecessary(View view) { 1287 if (view == mOverdrawChild) { 1288 mOverdrawChild = null; 1289 // only remove if we've added 1290 if (mChildDrawingOrderCallback != null) { 1291 mRecyclerView.setChildDrawingOrderCallback(null); 1292 } 1293 } 1294 } 1295 1296 /** 1297 * An interface which can be implemented by LayoutManager for better integration with 1298 * {@link ItemTouchHelper}. 1299 */ 1300 public static interface ViewDropHandler { 1301 1302 /** 1303 * Called by the {@link ItemTouchHelper} after a View is dropped over another View. 1304 * <p> 1305 * A LayoutManager should implement this interface to get ready for the upcoming move 1306 * operation. 1307 * <p> 1308 * For example, LinearLayoutManager sets up a "scrollToPositionWithOffset" calls so that 1309 * the View under drag will be used as an anchor View while calculating the next layout, 1310 * making layout stay consistent. 1311 * 1312 * @param view The View which is being dragged. It is very likely that user is still 1313 * dragging this View so there might be other 1314 * {@link #prepareForDrop(View, View, int, int)} after this one. 1315 * @param target The target view which is being dropped on. 1316 * @param x The <code>left</code> offset of the View that is being dragged. This value 1317 * includes the movement caused by the user. 1318 * @param y The <code>top</code> offset of the View that is being dragged. This value 1319 * includes the movement caused by the user. 1320 */ 1321 public void prepareForDrop(View view, View target, int x, int y); 1322 } 1323 1324 /** 1325 * This class is the contract between ItemTouchHelper and your application. It lets you control 1326 * which touch behaviors are enabled per each ViewHolder and also receive callbacks when user 1327 * performs these actions. 1328 * <p> 1329 * To control which actions user can take on each view, you should override 1330 * {@link #getMovementFlags(RecyclerView, ViewHolder)} and return appropriate set 1331 * of direction flags. ({@link #LEFT}, {@link #RIGHT}, {@link #START}, {@link #END}, 1332 * {@link #UP}, {@link #DOWN}). You can use 1333 * {@link #makeMovementFlags(int, int)} to easily construct it. Alternatively, you can use 1334 * {@link SimpleCallback}. 1335 * <p> 1336 * If user drags an item, ItemTouchHelper will call 1337 * {@link Callback#onMove(RecyclerView, ViewHolder, ViewHolder) 1338 * onMove(recyclerView, dragged, target)}. 1339 * Upon receiving this callback, you should move the item from the old position 1340 * ({@code dragged.getAdapterPosition()}) to new position ({@code target.getAdapterPosition()}) 1341 * in your adapter and also call {@link RecyclerView.Adapter#notifyItemMoved(int, int)}. 1342 * To control where a View can be dropped, you can override 1343 * {@link #canDropOver(RecyclerView, ViewHolder, ViewHolder)}. When a 1344 * dragging View overlaps multiple other views, Callback chooses the closest View with which 1345 * dragged View might have changed positions. Although this approach works for many use cases, 1346 * if you have a custom LayoutManager, you can override 1347 * {@link #chooseDropTarget(ViewHolder, java.util.List, int, int)} to select a 1348 * custom drop target. 1349 * <p> 1350 * When a View is swiped, ItemTouchHelper animates it until it goes out of bounds, then calls 1351 * {@link #onSwiped(ViewHolder, int)}. At this point, you should update your 1352 * adapter (e.g. remove the item) and call related Adapter#notify event. 1353 */ 1354 @SuppressWarnings("UnusedParameters") 1355 public abstract static class Callback { 1356 1357 public static final int DEFAULT_DRAG_ANIMATION_DURATION = 200; 1358 1359 public static final int DEFAULT_SWIPE_ANIMATION_DURATION = 250; 1360 1361 static final int RELATIVE_DIR_FLAGS = START | END | 1362 ((START | END) << DIRECTION_FLAG_COUNT) | 1363 ((START | END) << (2 * DIRECTION_FLAG_COUNT)); 1364 1365 private static final ItemTouchUIUtil sUICallback; 1366 1367 private static final int ABS_HORIZONTAL_DIR_FLAGS = LEFT | RIGHT | 1368 ((LEFT | RIGHT) << DIRECTION_FLAG_COUNT) | 1369 ((LEFT | RIGHT) << (2 * DIRECTION_FLAG_COUNT)); 1370 1371 private static final Interpolator sDragScrollInterpolator = new Interpolator() { 1372 public float getInterpolation(float t) { 1373 return t * t * t * t * t; 1374 } 1375 }; 1376 1377 private static final Interpolator sDragViewScrollCapInterpolator = new Interpolator() { 1378 public float getInterpolation(float t) { 1379 t -= 1.0f; 1380 return t * t * t * t * t + 1.0f; 1381 } 1382 }; 1383 1384 /** 1385 * Drag scroll speed keeps accelerating until this many milliseconds before being capped. 1386 */ 1387 private static final long DRAG_SCROLL_ACCELERATION_LIMIT_TIME_MS = 2000; 1388 1389 private int mCachedMaxScrollSpeed = -1; 1390 1391 static { 1392 if (Build.VERSION.SDK_INT >= 21) { 1393 sUICallback = new ItemTouchUIUtilImpl.Lollipop(); 1394 } else if (Build.VERSION.SDK_INT >= 11) { 1395 sUICallback = new ItemTouchUIUtilImpl.Honeycomb(); 1396 } else { 1397 sUICallback = new ItemTouchUIUtilImpl.Gingerbread(); 1398 } 1399 } 1400 1401 /** 1402 * Returns the {@link ItemTouchUIUtil} that is used by the {@link Callback} class for 1403 * visual 1404 * changes on Views in response to user interactions. {@link ItemTouchUIUtil} has different 1405 * implementations for different platform versions. 1406 * <p> 1407 * By default, {@link Callback} applies these changes on 1408 * {@link RecyclerView.ViewHolder#itemView}. 1409 * <p> 1410 * For example, if you have a use case where you only want the text to move when user 1411 * swipes over the view, you can do the following: 1412 * <pre> 1413 * public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder){ 1414 * getDefaultUIUtil().clearView(((ItemTouchViewHolder) viewHolder).textView); 1415 * } 1416 * public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { 1417 * if (viewHolder != null){ 1418 * getDefaultUIUtil().onSelected(((ItemTouchViewHolder) viewHolder).textView); 1419 * } 1420 * } 1421 * public void onChildDraw(Canvas c, RecyclerView recyclerView, 1422 * RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, 1423 * boolean isCurrentlyActive) { 1424 * getDefaultUIUtil().onDraw(c, recyclerView, 1425 * ((ItemTouchViewHolder) viewHolder).textView, dX, dY, 1426 * actionState, isCurrentlyActive); 1427 * return true; 1428 * } 1429 * public void onChildDrawOver(Canvas c, RecyclerView recyclerView, 1430 * RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, 1431 * boolean isCurrentlyActive) { 1432 * getDefaultUIUtil().onDrawOver(c, recyclerView, 1433 * ((ItemTouchViewHolder) viewHolder).textView, dX, dY, 1434 * actionState, isCurrentlyActive); 1435 * return true; 1436 * } 1437 * </pre> 1438 * 1439 * @return The {@link ItemTouchUIUtil} instance that is used by the {@link Callback} 1440 */ 1441 public static ItemTouchUIUtil getDefaultUIUtil() { 1442 return sUICallback; 1443 } 1444 1445 /** 1446 * Replaces a movement direction with its relative version by taking layout direction into 1447 * account. 1448 * 1449 * @param flags The flag value that include any number of movement flags. 1450 * @param layoutDirection The layout direction of the View. Can be obtained from 1451 * {@link ViewCompat#getLayoutDirection(android.view.View)}. 1452 * @return Updated flags which uses relative flags ({@link #START}, {@link #END}) instead 1453 * of {@link #LEFT}, {@link #RIGHT}. 1454 * @see #convertToAbsoluteDirection(int, int) 1455 */ 1456 public static int convertToRelativeDirection(int flags, int layoutDirection) { 1457 int masked = flags & ABS_HORIZONTAL_DIR_FLAGS; 1458 if (masked == 0) { 1459 return flags;// does not have any abs flags, good. 1460 } 1461 flags &= ~masked; //remove left / right. 1462 if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_LTR) { 1463 // no change. just OR with 2 bits shifted mask and return 1464 flags |= masked << 2; // START is 2 bits after LEFT, END is 2 bits after RIGHT. 1465 return flags; 1466 } else { 1467 // add RIGHT flag as START 1468 flags |= ((masked << 1) & ~ABS_HORIZONTAL_DIR_FLAGS); 1469 // first clean RIGHT bit then add LEFT flag as END 1470 flags |= ((masked << 1) & ABS_HORIZONTAL_DIR_FLAGS) << 2; 1471 } 1472 return flags; 1473 } 1474 1475 /** 1476 * Convenience method to create movement flags. 1477 * <p> 1478 * For instance, if you want to let your items be drag & dropped vertically and swiped 1479 * left to be dismissed, you can call this method with: 1480 * <code>makeMovementFlags(UP | DOWN, LEFT);</code> 1481 * 1482 * @param dragFlags The directions in which the item can be dragged. 1483 * @param swipeFlags The directions in which the item can be swiped. 1484 * @return Returns an integer composed of the given drag and swipe flags. 1485 */ 1486 public static int makeMovementFlags(int dragFlags, int swipeFlags) { 1487 return makeFlag(ACTION_STATE_IDLE, swipeFlags | dragFlags) | 1488 makeFlag(ACTION_STATE_SWIPE, swipeFlags) | makeFlag(ACTION_STATE_DRAG, 1489 dragFlags); 1490 } 1491 1492 /** 1493 * Shifts the given direction flags to the offset of the given action state. 1494 * 1495 * @param actionState The action state you want to get flags in. Should be one of 1496 * {@link #ACTION_STATE_IDLE}, {@link #ACTION_STATE_SWIPE} or 1497 * {@link #ACTION_STATE_DRAG}. 1498 * @param directions The direction flags. Can be composed from {@link #UP}, {@link #DOWN}, 1499 * {@link #RIGHT}, {@link #LEFT} {@link #START} and {@link #END}. 1500 * @return And integer that represents the given directions in the provided actionState. 1501 */ 1502 public static int makeFlag(int actionState, int directions) { 1503 return directions << (actionState * DIRECTION_FLAG_COUNT); 1504 } 1505 1506 /** 1507 * Should return a composite flag which defines the enabled move directions in each state 1508 * (idle, swiping, dragging). 1509 * <p> 1510 * Instead of composing this flag manually, you can use {@link #makeMovementFlags(int, 1511 * int)} 1512 * or {@link #makeFlag(int, int)}. 1513 * <p> 1514 * This flag is composed of 3 sets of 8 bits, where first 8 bits are for IDLE state, next 1515 * 8 bits are for SWIPE state and third 8 bits are for DRAG state. 1516 * Each 8 bit sections can be constructed by simply OR'ing direction flags defined in 1517 * {@link ItemTouchHelper}. 1518 * <p> 1519 * For example, if you want it to allow swiping LEFT and RIGHT but only allow starting to 1520 * swipe by swiping RIGHT, you can return: 1521 * <pre> 1522 * makeFlag(ACTION_STATE_IDLE, RIGHT) | makeFlag(ACTION_STATE_SWIPE, LEFT | RIGHT); 1523 * </pre> 1524 * This means, allow right movement while IDLE and allow right and left movement while 1525 * swiping. 1526 * 1527 * @param recyclerView The RecyclerView to which ItemTouchHelper is attached. 1528 * @param viewHolder The ViewHolder for which the movement information is necessary. 1529 * @return flags specifying which movements are allowed on this ViewHolder. 1530 * @see #makeMovementFlags(int, int) 1531 * @see #makeFlag(int, int) 1532 */ 1533 public abstract int getMovementFlags(RecyclerView recyclerView, 1534 ViewHolder viewHolder); 1535 1536 /** 1537 * Converts a given set of flags to absolution direction which means {@link #START} and 1538 * {@link #END} are replaced with {@link #LEFT} and {@link #RIGHT} depending on the layout 1539 * direction. 1540 * 1541 * @param flags The flag value that include any number of movement flags. 1542 * @param layoutDirection The layout direction of the RecyclerView. 1543 * @return Updated flags which includes only absolute direction values. 1544 */ 1545 public int convertToAbsoluteDirection(int flags, int layoutDirection) { 1546 int masked = flags & RELATIVE_DIR_FLAGS; 1547 if (masked == 0) { 1548 return flags;// does not have any relative flags, good. 1549 } 1550 flags &= ~masked; //remove start / end 1551 if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_LTR) { 1552 // no change. just OR with 2 bits shifted mask and return 1553 flags |= masked >> 2; // START is 2 bits after LEFT, END is 2 bits after RIGHT. 1554 return flags; 1555 } else { 1556 // add START flag as RIGHT 1557 flags |= ((masked >> 1) & ~RELATIVE_DIR_FLAGS); 1558 // first clean start bit then add END flag as LEFT 1559 flags |= ((masked >> 1) & RELATIVE_DIR_FLAGS) >> 2; 1560 } 1561 return flags; 1562 } 1563 1564 final int getAbsoluteMovementFlags(RecyclerView recyclerView, 1565 ViewHolder viewHolder) { 1566 final int flags = getMovementFlags(recyclerView, viewHolder); 1567 return convertToAbsoluteDirection(flags, ViewCompat.getLayoutDirection(recyclerView)); 1568 } 1569 1570 private boolean hasDragFlag(RecyclerView recyclerView, ViewHolder viewHolder) { 1571 final int flags = getAbsoluteMovementFlags(recyclerView, viewHolder); 1572 return (flags & ACTION_MODE_DRAG_MASK) != 0; 1573 } 1574 1575 private boolean hasSwipeFlag(RecyclerView recyclerView, 1576 ViewHolder viewHolder) { 1577 final int flags = getAbsoluteMovementFlags(recyclerView, viewHolder); 1578 return (flags & ACTION_MODE_SWIPE_MASK) != 0; 1579 } 1580 1581 /** 1582 * Return true if the current ViewHolder can be dropped over the the target ViewHolder. 1583 * <p> 1584 * This method is used when selecting drop target for the dragged View. After Views are 1585 * eliminated either via bounds check or via this method, resulting set of views will be 1586 * passed to {@link #chooseDropTarget(ViewHolder, java.util.List, int, int)}. 1587 * <p> 1588 * Default implementation returns true. 1589 * 1590 * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to. 1591 * @param current The ViewHolder that user is dragging. 1592 * @param target The ViewHolder which is below the dragged ViewHolder. 1593 * @return True if the dragged ViewHolder can be replaced with the target ViewHolder, false 1594 * otherwise. 1595 */ 1596 public boolean canDropOver(RecyclerView recyclerView, ViewHolder current, 1597 ViewHolder target) { 1598 return true; 1599 } 1600 1601 /** 1602 * Called when ItemTouchHelper wants to move the dragged item from its old position to 1603 * the new position. 1604 * <p> 1605 * If this method returns true, ItemTouchHelper assumes {@code viewHolder} has been moved 1606 * to the adapter position of {@code target} ViewHolder 1607 * ({@link ViewHolder#getAdapterPosition() 1608 * ViewHolder#getAdapterPosition()}). 1609 * <p> 1610 * If you don't support drag & drop, this method will never be called. 1611 * 1612 * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to. 1613 * @param viewHolder The ViewHolder which is being dragged by the user. 1614 * @param target The ViewHolder over which the currently active item is being 1615 * dragged. 1616 * @return True if the {@code viewHolder} has been moved to the adapter position of 1617 * {@code target}. 1618 * @see #onMoved(RecyclerView, ViewHolder, int, ViewHolder, int, int, int) 1619 */ 1620 public abstract boolean onMove(RecyclerView recyclerView, 1621 ViewHolder viewHolder, ViewHolder target); 1622 1623 /** 1624 * Returns whether ItemTouchHelper should start a drag and drop operation if an item is 1625 * long pressed. 1626 * <p> 1627 * Default value returns true but you may want to disable this if you want to start 1628 * dragging on a custom view touch using {@link #startDrag(ViewHolder)}. 1629 * 1630 * @return True if ItemTouchHelper should start dragging an item when it is long pressed, 1631 * false otherwise. Default value is <code>true</code>. 1632 * @see #startDrag(ViewHolder) 1633 */ 1634 public boolean isLongPressDragEnabled() { 1635 return true; 1636 } 1637 1638 /** 1639 * Returns whether ItemTouchHelper should start a swipe operation if a pointer is swiped 1640 * over the View. 1641 * <p> 1642 * Default value returns true but you may want to disable this if you want to start 1643 * swiping on a custom view touch using {@link #startSwipe(ViewHolder)}. 1644 * 1645 * @return True if ItemTouchHelper should start swiping an item when user swipes a pointer 1646 * over the View, false otherwise. Default value is <code>true</code>. 1647 * @see #startSwipe(ViewHolder) 1648 */ 1649 public boolean isItemViewSwipeEnabled() { 1650 return true; 1651 } 1652 1653 /** 1654 * When finding views under a dragged view, by default, ItemTouchHelper searches for views 1655 * that overlap with the dragged View. By overriding this method, you can extend or shrink 1656 * the search box. 1657 * 1658 * @return The extra margin to be added to the hit box of the dragged View. 1659 */ 1660 public int getBoundingBoxMargin() { 1661 return 0; 1662 } 1663 1664 /** 1665 * Returns the fraction that the user should move the View to be considered as swiped. 1666 * The fraction is calculated with respect to RecyclerView's bounds. 1667 * <p> 1668 * Default value is .5f, which means, to swipe a View, user must move the View at least 1669 * half of RecyclerView's width or height, depending on the swipe direction. 1670 * 1671 * @param viewHolder The ViewHolder that is being dragged. 1672 * @return A float value that denotes the fraction of the View size. Default value 1673 * is .5f . 1674 */ 1675 public float getSwipeThreshold(ViewHolder viewHolder) { 1676 return .5f; 1677 } 1678 1679 /** 1680 * Returns the fraction that the user should move the View to be considered as it is 1681 * dragged. After a view is moved this amount, ItemTouchHelper starts checking for Views 1682 * below it for a possible drop. 1683 * 1684 * @param viewHolder The ViewHolder that is being dragged. 1685 * @return A float value that denotes the fraction of the View size. Default value is 1686 * .5f . 1687 */ 1688 public float getMoveThreshold(ViewHolder viewHolder) { 1689 return .5f; 1690 } 1691 1692 /** 1693 * Defines the minimum velocity which will be considered as a swipe action by the user. 1694 * <p> 1695 * You can increase this value to make it harder to swipe or decrease it to make it easier. 1696 * Keep in mind that ItemTouchHelper also checks the perpendicular velocity and makes sure 1697 * current direction velocity is larger then the perpendicular one. Otherwise, user's 1698 * movement is ambiguous. You can change the threshold by overriding 1699 * {@link #getSwipeVelocityThreshold(float)}. 1700 * <p> 1701 * The velocity is calculated in pixels per second. 1702 * <p> 1703 * The default framework value is passed as a parameter so that you can modify it with a 1704 * multiplier. 1705 * 1706 * @param defaultValue The default value (in pixels per second) used by the 1707 * ItemTouchHelper. 1708 * @return The minimum swipe velocity. The default implementation returns the 1709 * <code>defaultValue</code> parameter. 1710 * @see #getSwipeVelocityThreshold(float) 1711 * @see #getSwipeThreshold(ViewHolder) 1712 */ 1713 public float getSwipeEscapeVelocity(float defaultValue) { 1714 return defaultValue; 1715 } 1716 1717 /** 1718 * Defines the maximum velocity ItemTouchHelper will ever calculate for pointer movements. 1719 * <p> 1720 * To consider a movement as swipe, ItemTouchHelper requires it to be larger than the 1721 * perpendicular movement. If both directions reach to the max threshold, none of them will 1722 * be considered as a swipe because it is usually an indication that user rather tried to 1723 * scroll then swipe. 1724 * <p> 1725 * The velocity is calculated in pixels per second. 1726 * <p> 1727 * You can customize this behavior by changing this method. If you increase the value, it 1728 * will be easier for the user to swipe diagonally and if you decrease the value, user will 1729 * need to make a rather straight finger movement to trigger a swipe. 1730 * 1731 * @param defaultValue The default value(in pixels per second) used by the ItemTouchHelper. 1732 * @return The velocity cap for pointer movements. The default implementation returns the 1733 * <code>defaultValue</code> parameter. 1734 * @see #getSwipeEscapeVelocity(float) 1735 */ 1736 public float getSwipeVelocityThreshold(float defaultValue) { 1737 return defaultValue; 1738 } 1739 1740 /** 1741 * Called by ItemTouchHelper to select a drop target from the list of ViewHolders that 1742 * are under the dragged View. 1743 * <p> 1744 * Default implementation filters the View with which dragged item have changed position 1745 * in the drag direction. For instance, if the view is dragged UP, it compares the 1746 * <code>view.getTop()</code> of the two views before and after drag started. If that value 1747 * is different, the target view passes the filter. 1748 * <p> 1749 * Among these Views which pass the test, the one closest to the dragged view is chosen. 1750 * <p> 1751 * This method is called on the main thread every time user moves the View. If you want to 1752 * override it, make sure it does not do any expensive operations. 1753 * 1754 * @param selected The ViewHolder being dragged by the user. 1755 * @param dropTargets The list of ViewHolder that are under the dragged View and 1756 * candidate as a drop. 1757 * @param curX The updated left value of the dragged View after drag translations 1758 * are applied. This value does not include margins added by 1759 * {@link RecyclerView.ItemDecoration}s. 1760 * @param curY The updated top value of the dragged View after drag translations 1761 * are applied. This value does not include margins added by 1762 * {@link RecyclerView.ItemDecoration}s. 1763 * @return A ViewHolder to whose position the dragged ViewHolder should be 1764 * moved to. 1765 */ 1766 public ViewHolder chooseDropTarget(ViewHolder selected, 1767 List<ViewHolder> dropTargets, int curX, int curY) { 1768 int right = curX + selected.itemView.getWidth(); 1769 int bottom = curY + selected.itemView.getHeight(); 1770 ViewHolder winner = null; 1771 int winnerScore = -1; 1772 final int dx = curX - selected.itemView.getLeft(); 1773 final int dy = curY - selected.itemView.getTop(); 1774 final int targetsSize = dropTargets.size(); 1775 for (int i = 0; i < targetsSize; i++) { 1776 final ViewHolder target = dropTargets.get(i); 1777 if (dx > 0) { 1778 int diff = target.itemView.getRight() - right; 1779 if (diff < 0 && target.itemView.getRight() > selected.itemView.getRight()) { 1780 final int score = Math.abs(diff); 1781 if (score > winnerScore) { 1782 winnerScore = score; 1783 winner = target; 1784 } 1785 } 1786 } 1787 if (dx < 0) { 1788 int diff = target.itemView.getLeft() - curX; 1789 if (diff > 0 && target.itemView.getLeft() < selected.itemView.getLeft()) { 1790 final int score = Math.abs(diff); 1791 if (score > winnerScore) { 1792 winnerScore = score; 1793 winner = target; 1794 } 1795 } 1796 } 1797 if (dy < 0) { 1798 int diff = target.itemView.getTop() - curY; 1799 if (diff > 0 && target.itemView.getTop() < selected.itemView.getTop()) { 1800 final int score = Math.abs(diff); 1801 if (score > winnerScore) { 1802 winnerScore = score; 1803 winner = target; 1804 } 1805 } 1806 } 1807 1808 if (dy > 0) { 1809 int diff = target.itemView.getBottom() - bottom; 1810 if (diff < 0 && target.itemView.getBottom() > selected.itemView.getBottom()) { 1811 final int score = Math.abs(diff); 1812 if (score > winnerScore) { 1813 winnerScore = score; 1814 winner = target; 1815 } 1816 } 1817 } 1818 } 1819 return winner; 1820 } 1821 1822 /** 1823 * Called when a ViewHolder is swiped by the user. 1824 * <p> 1825 * If you are returning relative directions ({@link #START} , {@link #END}) from the 1826 * {@link #getMovementFlags(RecyclerView, ViewHolder)} method, this method 1827 * will also use relative directions. Otherwise, it will use absolute directions. 1828 * <p> 1829 * If you don't support swiping, this method will never be called. 1830 * <p> 1831 * ItemTouchHelper will keep a reference to the View until it is detached from 1832 * RecyclerView. 1833 * As soon as it is detached, ItemTouchHelper will call 1834 * {@link #clearView(RecyclerView, ViewHolder)}. 1835 * 1836 * @param viewHolder The ViewHolder which has been swiped by the user. 1837 * @param direction The direction to which the ViewHolder is swiped. It is one of 1838 * {@link #UP}, {@link #DOWN}, 1839 * {@link #LEFT} or {@link #RIGHT}. If your 1840 * {@link #getMovementFlags(RecyclerView, ViewHolder)} 1841 * method 1842 * returned relative flags instead of {@link #LEFT} / {@link #RIGHT}; 1843 * `direction` will be relative as well. ({@link #START} or {@link 1844 * #END}). 1845 */ 1846 public abstract void onSwiped(ViewHolder viewHolder, int direction); 1847 1848 /** 1849 * Called when the ViewHolder swiped or dragged by the ItemTouchHelper is changed. 1850 * <p/> 1851 * If you override this method, you should call super. 1852 * 1853 * @param viewHolder The new ViewHolder that is being swiped or dragged. Might be null if 1854 * it is cleared. 1855 * @param actionState One of {@link ItemTouchHelper#ACTION_STATE_IDLE}, 1856 * {@link ItemTouchHelper#ACTION_STATE_SWIPE} or 1857 * {@link ItemTouchHelper#ACTION_STATE_DRAG}. 1858 * @see #clearView(RecyclerView, RecyclerView.ViewHolder) 1859 */ 1860 public void onSelectedChanged(ViewHolder viewHolder, int actionState) { 1861 if (viewHolder != null) { 1862 sUICallback.onSelected(viewHolder.itemView); 1863 } 1864 } 1865 1866 private int getMaxDragScroll(RecyclerView recyclerView) { 1867 if (mCachedMaxScrollSpeed == -1) { 1868 mCachedMaxScrollSpeed = recyclerView.getResources().getDimensionPixelSize( 1869 R.dimen.item_touch_helper_max_drag_scroll_per_frame); 1870 } 1871 return mCachedMaxScrollSpeed; 1872 } 1873 1874 /** 1875 * Called when {@link #onMove(RecyclerView, ViewHolder, ViewHolder)} returns true. 1876 * <p> 1877 * ItemTouchHelper does not create an extra Bitmap or View while dragging, instead, it 1878 * modifies the existing View. Because of this reason, it is important that the View is 1879 * still part of the layout after it is moved. This may not work as intended when swapped 1880 * Views are close to RecyclerView bounds or there are gaps between them (e.g. other Views 1881 * which were not eligible for dropping over). 1882 * <p> 1883 * This method is responsible to give necessary hint to the LayoutManager so that it will 1884 * keep the View in visible area. For example, for LinearLayoutManager, this is as simple 1885 * as calling {@link LinearLayoutManager#scrollToPositionWithOffset(int, int)}. 1886 * 1887 * Default implementation calls {@link RecyclerView#scrollToPosition(int)} if the View's 1888 * new position is likely to be out of bounds. 1889 * <p> 1890 * It is important to ensure the ViewHolder will stay visible as otherwise, it might be 1891 * removed by the LayoutManager if the move causes the View to go out of bounds. In that 1892 * case, drag will end prematurely. 1893 * 1894 * @param recyclerView The RecyclerView controlled by the ItemTouchHelper. 1895 * @param viewHolder The ViewHolder under user's control. 1896 * @param fromPos The previous adapter position of the dragged item (before it was 1897 * moved). 1898 * @param target The ViewHolder on which the currently active item has been dropped. 1899 * @param toPos The new adapter position of the dragged item. 1900 * @param x The updated left value of the dragged View after drag translations 1901 * are applied. This value does not include margins added by 1902 * {@link RecyclerView.ItemDecoration}s. 1903 * @param y The updated top value of the dragged View after drag translations 1904 * are applied. This value does not include margins added by 1905 * {@link RecyclerView.ItemDecoration}s. 1906 */ 1907 public void onMoved(final RecyclerView recyclerView, 1908 final ViewHolder viewHolder, int fromPos, final ViewHolder target, int toPos, int x, 1909 int y) { 1910 final RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); 1911 if (layoutManager instanceof ViewDropHandler) { 1912 ((ViewDropHandler) layoutManager).prepareForDrop(viewHolder.itemView, 1913 target.itemView, x, y); 1914 return; 1915 } 1916 1917 // if layout manager cannot handle it, do some guesswork 1918 if (layoutManager.canScrollHorizontally()) { 1919 final int minLeft = layoutManager.getDecoratedLeft(target.itemView); 1920 if (minLeft <= recyclerView.getPaddingLeft()) { 1921 recyclerView.scrollToPosition(toPos); 1922 } 1923 final int maxRight = layoutManager.getDecoratedRight(target.itemView); 1924 if (maxRight >= recyclerView.getWidth() - recyclerView.getPaddingRight()) { 1925 recyclerView.scrollToPosition(toPos); 1926 } 1927 } 1928 1929 if (layoutManager.canScrollVertically()) { 1930 final int minTop = layoutManager.getDecoratedTop(target.itemView); 1931 if (minTop <= recyclerView.getPaddingTop()) { 1932 recyclerView.scrollToPosition(toPos); 1933 } 1934 final int maxBottom = layoutManager.getDecoratedBottom(target.itemView); 1935 if (maxBottom >= recyclerView.getHeight() - recyclerView.getPaddingBottom()) { 1936 recyclerView.scrollToPosition(toPos); 1937 } 1938 } 1939 } 1940 1941 private void onDraw(Canvas c, RecyclerView parent, ViewHolder selected, 1942 List<ItemTouchHelper.RecoverAnimation> recoverAnimationList, 1943 int actionState, float dX, float dY) { 1944 final int recoverAnimSize = recoverAnimationList.size(); 1945 for (int i = 0; i < recoverAnimSize; i++) { 1946 final ItemTouchHelper.RecoverAnimation anim = recoverAnimationList.get(i); 1947 anim.update(); 1948 final int count = c.save(); 1949 onChildDraw(c, parent, anim.mViewHolder, anim.mX, anim.mY, anim.mActionState, 1950 false); 1951 c.restoreToCount(count); 1952 } 1953 if (selected != null) { 1954 final int count = c.save(); 1955 onChildDraw(c, parent, selected, dX, dY, actionState, true); 1956 c.restoreToCount(count); 1957 } 1958 } 1959 1960 private void onDrawOver(Canvas c, RecyclerView parent, ViewHolder selected, 1961 List<ItemTouchHelper.RecoverAnimation> recoverAnimationList, 1962 int actionState, float dX, float dY) { 1963 final int recoverAnimSize = recoverAnimationList.size(); 1964 for (int i = 0; i < recoverAnimSize; i++) { 1965 final ItemTouchHelper.RecoverAnimation anim = recoverAnimationList.get(i); 1966 final int count = c.save(); 1967 onChildDrawOver(c, parent, anim.mViewHolder, anim.mX, anim.mY, anim.mActionState, 1968 false); 1969 c.restoreToCount(count); 1970 } 1971 if (selected != null) { 1972 final int count = c.save(); 1973 onChildDrawOver(c, parent, selected, dX, dY, actionState, true); 1974 c.restoreToCount(count); 1975 } 1976 boolean hasRunningAnimation = false; 1977 for (int i = recoverAnimSize - 1; i >= 0; i--) { 1978 final RecoverAnimation anim = recoverAnimationList.get(i); 1979 if (anim.mEnded && !anim.mIsPendingCleanup) { 1980 recoverAnimationList.remove(i); 1981 } else if (!anim.mEnded) { 1982 hasRunningAnimation = true; 1983 } 1984 } 1985 if (hasRunningAnimation) { 1986 parent.invalidate(); 1987 } 1988 } 1989 1990 /** 1991 * Called by the ItemTouchHelper when the user interaction with an element is over and it 1992 * also completed its animation. 1993 * <p> 1994 * This is a good place to clear all changes on the View that was done in 1995 * {@link #onSelectedChanged(RecyclerView.ViewHolder, int)}, 1996 * {@link #onChildDraw(Canvas, RecyclerView, ViewHolder, float, float, int, 1997 * boolean)} or 1998 * {@link #onChildDrawOver(Canvas, RecyclerView, ViewHolder, float, float, int, boolean)}. 1999 * 2000 * @param recyclerView The RecyclerView which is controlled by the ItemTouchHelper. 2001 * @param viewHolder The View that was interacted by the user. 2002 */ 2003 public void clearView(RecyclerView recyclerView, ViewHolder viewHolder) { 2004 sUICallback.clearView(viewHolder.itemView); 2005 } 2006 2007 /** 2008 * Called by ItemTouchHelper on RecyclerView's onDraw callback. 2009 * <p> 2010 * If you would like to customize how your View's respond to user interactions, this is 2011 * a good place to override. 2012 * <p> 2013 * Default implementation translates the child by the given <code>dX</code>, 2014 * <code>dY</code>. 2015 * ItemTouchHelper also takes care of drawing the child after other children if it is being 2016 * dragged. This is done using child re-ordering mechanism. On platforms prior to L, this 2017 * is 2018 * achieved via {@link android.view.ViewGroup#getChildDrawingOrder(int, int)} and on L 2019 * and after, it changes View's elevation value to be greater than all other children.) 2020 * 2021 * @param c The canvas which RecyclerView is drawing its children 2022 * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to 2023 * @param viewHolder The ViewHolder which is being interacted by the User or it was 2024 * interacted and simply animating to its original position 2025 * @param dX The amount of horizontal displacement caused by user's action 2026 * @param dY The amount of vertical displacement caused by user's action 2027 * @param actionState The type of interaction on the View. Is either {@link 2028 * #ACTION_STATE_DRAG} or {@link #ACTION_STATE_SWIPE}. 2029 * @param isCurrentlyActive True if this view is currently being controlled by the user or 2030 * false it is simply animating back to its original state. 2031 * @see #onChildDrawOver(Canvas, RecyclerView, ViewHolder, float, float, int, 2032 * boolean) 2033 */ 2034 public void onChildDraw(Canvas c, RecyclerView recyclerView, 2035 ViewHolder viewHolder, 2036 float dX, float dY, int actionState, boolean isCurrentlyActive) { 2037 sUICallback.onDraw(c, recyclerView, viewHolder.itemView, dX, dY, actionState, 2038 isCurrentlyActive); 2039 } 2040 2041 /** 2042 * Called by ItemTouchHelper on RecyclerView's onDraw callback. 2043 * <p> 2044 * If you would like to customize how your View's respond to user interactions, this is 2045 * a good place to override. 2046 * <p> 2047 * Default implementation translates the child by the given <code>dX</code>, 2048 * <code>dY</code>. 2049 * ItemTouchHelper also takes care of drawing the child after other children if it is being 2050 * dragged. This is done using child re-ordering mechanism. On platforms prior to L, this 2051 * is 2052 * achieved via {@link android.view.ViewGroup#getChildDrawingOrder(int, int)} and on L 2053 * and after, it changes View's elevation value to be greater than all other children.) 2054 * 2055 * @param c The canvas which RecyclerView is drawing its children 2056 * @param recyclerView The RecyclerView to which ItemTouchHelper is attached to 2057 * @param viewHolder The ViewHolder which is being interacted by the User or it was 2058 * interacted and simply animating to its original position 2059 * @param dX The amount of horizontal displacement caused by user's action 2060 * @param dY The amount of vertical displacement caused by user's action 2061 * @param actionState The type of interaction on the View. Is either {@link 2062 * #ACTION_STATE_DRAG} or {@link #ACTION_STATE_SWIPE}. 2063 * @param isCurrentlyActive True if this view is currently being controlled by the user or 2064 * false it is simply animating back to its original state. 2065 * @see #onChildDrawOver(Canvas, RecyclerView, ViewHolder, float, float, int, 2066 * boolean) 2067 */ 2068 public void onChildDrawOver(Canvas c, RecyclerView recyclerView, 2069 ViewHolder viewHolder, 2070 float dX, float dY, int actionState, boolean isCurrentlyActive) { 2071 sUICallback.onDrawOver(c, recyclerView, viewHolder.itemView, dX, dY, actionState, 2072 isCurrentlyActive); 2073 } 2074 2075 /** 2076 * Called by the ItemTouchHelper when user action finished on a ViewHolder and now the View 2077 * will be animated to its final position. 2078 * <p> 2079 * Default implementation uses ItemAnimator's duration values. If 2080 * <code>animationType</code> is {@link #ANIMATION_TYPE_DRAG}, it returns 2081 * {@link RecyclerView.ItemAnimator#getMoveDuration()}, otherwise, it returns 2082 * {@link RecyclerView.ItemAnimator#getRemoveDuration()}. If RecyclerView does not have 2083 * any {@link RecyclerView.ItemAnimator} attached, this method returns 2084 * {@code DEFAULT_DRAG_ANIMATION_DURATION} or {@code DEFAULT_SWIPE_ANIMATION_DURATION} 2085 * depending on the animation type. 2086 * 2087 * @param recyclerView The RecyclerView to which the ItemTouchHelper is attached to. 2088 * @param animationType The type of animation. Is one of {@link #ANIMATION_TYPE_DRAG}, 2089 * {@link #ANIMATION_TYPE_SWIPE_CANCEL} or 2090 * {@link #ANIMATION_TYPE_SWIPE_SUCCESS}. 2091 * @param animateDx The horizontal distance that the animation will offset 2092 * @param animateDy The vertical distance that the animation will offset 2093 * @return The duration for the animation 2094 */ 2095 public long getAnimationDuration(RecyclerView recyclerView, int animationType, 2096 float animateDx, float animateDy) { 2097 final RecyclerView.ItemAnimator itemAnimator = recyclerView.getItemAnimator(); 2098 if (itemAnimator == null) { 2099 return animationType == ANIMATION_TYPE_DRAG ? DEFAULT_DRAG_ANIMATION_DURATION 2100 : DEFAULT_SWIPE_ANIMATION_DURATION; 2101 } else { 2102 return animationType == ANIMATION_TYPE_DRAG ? itemAnimator.getMoveDuration() 2103 : itemAnimator.getRemoveDuration(); 2104 } 2105 } 2106 2107 /** 2108 * Called by the ItemTouchHelper when user is dragging a view out of bounds. 2109 * <p> 2110 * You can override this method to decide how much RecyclerView should scroll in response 2111 * to this action. Default implementation calculates a value based on the amount of View 2112 * out of bounds and the time it spent there. The longer user keeps the View out of bounds, 2113 * the faster the list will scroll. Similarly, the larger portion of the View is out of 2114 * bounds, the faster the RecyclerView will scroll. 2115 * 2116 * @param recyclerView The RecyclerView instance to which ItemTouchHelper is 2117 * attached to. 2118 * @param viewSize The total size of the View in scroll direction, excluding 2119 * item decorations. 2120 * @param viewSizeOutOfBounds The total size of the View that is out of bounds. This value 2121 * is negative if the View is dragged towards left or top edge. 2122 * @param totalSize The total size of RecyclerView in the scroll direction. 2123 * @param msSinceStartScroll The time passed since View is kept out of bounds. 2124 * @return The amount that RecyclerView should scroll. Keep in mind that this value will 2125 * be passed to {@link RecyclerView#scrollBy(int, int)} method. 2126 */ 2127 public int interpolateOutOfBoundsScroll(RecyclerView recyclerView, 2128 int viewSize, int viewSizeOutOfBounds, 2129 int totalSize, long msSinceStartScroll) { 2130 final int maxScroll = getMaxDragScroll(recyclerView); 2131 final int absOutOfBounds = Math.abs(viewSizeOutOfBounds); 2132 final int direction = (int) Math.signum(viewSizeOutOfBounds); 2133 // might be negative if other direction 2134 float outOfBoundsRatio = Math.min(1f, 1f * absOutOfBounds / viewSize); 2135 final int cappedScroll = (int) (direction * maxScroll * 2136 sDragViewScrollCapInterpolator.getInterpolation(outOfBoundsRatio)); 2137 final float timeRatio; 2138 if (msSinceStartScroll > DRAG_SCROLL_ACCELERATION_LIMIT_TIME_MS) { 2139 timeRatio = 1f; 2140 } else { 2141 timeRatio = (float) msSinceStartScroll / DRAG_SCROLL_ACCELERATION_LIMIT_TIME_MS; 2142 } 2143 final int value = (int) (cappedScroll * sDragScrollInterpolator 2144 .getInterpolation(timeRatio)); 2145 if (value == 0) { 2146 return viewSizeOutOfBounds > 0 ? 1 : -1; 2147 } 2148 return value; 2149 } 2150 } 2151 2152 /** 2153 * A simple wrapper to the default Callback which you can construct with drag and swipe 2154 * directions and this class will handle the flag callbacks. You should still override onMove 2155 * or 2156 * onSwiped depending on your use case. 2157 * 2158 * <pre> 2159 * ItemTouchHelper mIth = new ItemTouchHelper( 2160 * new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN, 2161 * ItemTouchHelper.LEFT) { 2162 * public abstract boolean onMove(RecyclerView recyclerView, 2163 * ViewHolder viewHolder, ViewHolder target) { 2164 * final int fromPos = viewHolder.getAdapterPosition(); 2165 * final int toPos = viewHolder.getAdapterPosition(); 2166 * // move item in `fromPos` to `toPos` in adapter. 2167 * return true;// true if moved, false otherwise 2168 * } 2169 * public void onSwiped(ViewHolder viewHolder, int direction) { 2170 * // remove from adapter 2171 * } 2172 * }); 2173 * </pre> 2174 */ 2175 public abstract static class SimpleCallback extends Callback { 2176 2177 private int mDefaultSwipeDirs; 2178 2179 private int mDefaultDragDirs; 2180 2181 /** 2182 * Creates a Callback for the given drag and swipe allowance. These values serve as 2183 * defaults 2184 * and if you want to customize behavior per ViewHolder, you can override 2185 * {@link #getSwipeDirs(RecyclerView, ViewHolder)} 2186 * and / or {@link #getDragDirs(RecyclerView, ViewHolder)}. 2187 * 2188 * @param dragDirs Binary OR of direction flags in which the Views can be dragged. Must be 2189 * composed of {@link #LEFT}, {@link #RIGHT}, {@link #START}, {@link 2190 * #END}, 2191 * {@link #UP} and {@link #DOWN}. 2192 * @param swipeDirs Binary OR of direction flags in which the Views can be swiped. Must be 2193 * composed of {@link #LEFT}, {@link #RIGHT}, {@link #START}, {@link 2194 * #END}, 2195 * {@link #UP} and {@link #DOWN}. 2196 */ 2197 public SimpleCallback(int dragDirs, int swipeDirs) { 2198 mDefaultSwipeDirs = swipeDirs; 2199 mDefaultDragDirs = dragDirs; 2200 } 2201 2202 /** 2203 * Updates the default swipe directions. For example, you can use this method to toggle 2204 * certain directions depending on your use case. 2205 * 2206 * @param defaultSwipeDirs Binary OR of directions in which the ViewHolders can be swiped. 2207 */ 2208 public void setDefaultSwipeDirs(int defaultSwipeDirs) { 2209 mDefaultSwipeDirs = defaultSwipeDirs; 2210 } 2211 2212 /** 2213 * Updates the default drag directions. For example, you can use this method to toggle 2214 * certain directions depending on your use case. 2215 * 2216 * @param defaultDragDirs Binary OR of directions in which the ViewHolders can be dragged. 2217 */ 2218 public void setDefaultDragDirs(int defaultDragDirs) { 2219 mDefaultDragDirs = defaultDragDirs; 2220 } 2221 2222 /** 2223 * Returns the swipe directions for the provided ViewHolder. 2224 * Default implementation returns the swipe directions that was set via constructor or 2225 * {@link #setDefaultSwipeDirs(int)}. 2226 * 2227 * @param recyclerView The RecyclerView to which the ItemTouchHelper is attached to. 2228 * @param viewHolder The RecyclerView for which the swipe drection is queried. 2229 * @return A binary OR of direction flags. 2230 */ 2231 public int getSwipeDirs(RecyclerView recyclerView, ViewHolder viewHolder) { 2232 return mDefaultSwipeDirs; 2233 } 2234 2235 /** 2236 * Returns the drag directions for the provided ViewHolder. 2237 * Default implementation returns the drag directions that was set via constructor or 2238 * {@link #setDefaultDragDirs(int)}. 2239 * 2240 * @param recyclerView The RecyclerView to which the ItemTouchHelper is attached to. 2241 * @param viewHolder The RecyclerView for which the swipe drection is queried. 2242 * @return A binary OR of direction flags. 2243 */ 2244 public int getDragDirs(RecyclerView recyclerView, ViewHolder viewHolder) { 2245 return mDefaultDragDirs; 2246 } 2247 2248 @Override 2249 public int getMovementFlags(RecyclerView recyclerView, ViewHolder viewHolder) { 2250 return makeMovementFlags(getDragDirs(recyclerView, viewHolder), 2251 getSwipeDirs(recyclerView, viewHolder)); 2252 } 2253 } 2254 2255 private class ItemTouchHelperGestureListener extends GestureDetector.SimpleOnGestureListener { 2256 2257 @Override 2258 public boolean onDown(MotionEvent e) { 2259 return true; 2260 } 2261 2262 @Override 2263 public void onLongPress(MotionEvent e) { 2264 View child = findChildView(e); 2265 if (child != null) { 2266 ViewHolder vh = mRecyclerView.getChildViewHolder(child); 2267 if (vh != null) { 2268 if (!mCallback.hasDragFlag(mRecyclerView, vh)) { 2269 return; 2270 } 2271 int pointerId = e.getPointerId(0); 2272 // Long press is deferred. 2273 // Check w/ active pointer id to avoid selecting after motion 2274 // event is canceled. 2275 if (pointerId == mActivePointerId) { 2276 final int index = e.findPointerIndex(mActivePointerId); 2277 final float x = e.getX(index); 2278 final float y = e.getY(index); 2279 mInitialTouchX = x; 2280 mInitialTouchY = y; 2281 mDx = mDy = 0f; 2282 if (DEBUG) { 2283 Log.d(TAG, 2284 "onlong press: x:" + mInitialTouchX + ",y:" + mInitialTouchY); 2285 } 2286 if (mCallback.isLongPressDragEnabled()) { 2287 select(vh, ACTION_STATE_DRAG); 2288 } 2289 } 2290 } 2291 } 2292 } 2293 } 2294 2295 private class RecoverAnimation implements AnimatorListenerCompat { 2296 2297 final float mStartDx; 2298 2299 final float mStartDy; 2300 2301 final float mTargetX; 2302 2303 final float mTargetY; 2304 2305 final ViewHolder mViewHolder; 2306 2307 final int mActionState; 2308 2309 private final ValueAnimatorCompat mValueAnimator; 2310 2311 private final int mAnimationType; 2312 2313 public boolean mIsPendingCleanup; 2314 2315 float mX; 2316 2317 float mY; 2318 2319 // if user starts touching a recovering view, we put it into interaction mode again, 2320 // instantly. 2321 boolean mOverridden = false; 2322 2323 private boolean mEnded = false; 2324 2325 private float mFraction; 2326 2327 public RecoverAnimation(ViewHolder viewHolder, int animationType, 2328 int actionState, float startDx, float startDy, float targetX, float targetY) { 2329 mActionState = actionState; 2330 mAnimationType = animationType; 2331 mViewHolder = viewHolder; 2332 mStartDx = startDx; 2333 mStartDy = startDy; 2334 mTargetX = targetX; 2335 mTargetY = targetY; 2336 mValueAnimator = AnimatorCompatHelper.emptyValueAnimator(); 2337 mValueAnimator.addUpdateListener( 2338 new AnimatorUpdateListenerCompat() { 2339 @Override 2340 public void onAnimationUpdate(ValueAnimatorCompat animation) { 2341 setFraction(animation.getAnimatedFraction()); 2342 } 2343 }); 2344 mValueAnimator.setTarget(viewHolder.itemView); 2345 mValueAnimator.addListener(this); 2346 setFraction(0f); 2347 } 2348 2349 public void setDuration(long duration) { 2350 mValueAnimator.setDuration(duration); 2351 } 2352 2353 public void start() { 2354 mViewHolder.setIsRecyclable(false); 2355 mValueAnimator.start(); 2356 } 2357 2358 public void cancel() { 2359 mValueAnimator.cancel(); 2360 } 2361 2362 public void setFraction(float fraction) { 2363 mFraction = fraction; 2364 } 2365 2366 /** 2367 * We run updates on onDraw method but use the fraction from animator callback. 2368 * This way, we can sync translate x/y values w/ the animators to avoid one-off frames. 2369 */ 2370 public void update() { 2371 if (mStartDx == mTargetX) { 2372 mX = ViewCompat.getTranslationX(mViewHolder.itemView); 2373 } else { 2374 mX = mStartDx + mFraction * (mTargetX - mStartDx); 2375 } 2376 if (mStartDy == mTargetY) { 2377 mY = ViewCompat.getTranslationY(mViewHolder.itemView); 2378 } else { 2379 mY = mStartDy + mFraction * (mTargetY - mStartDy); 2380 } 2381 } 2382 2383 @Override 2384 public void onAnimationStart(ValueAnimatorCompat animation) { 2385 2386 } 2387 2388 @Override 2389 public void onAnimationEnd(ValueAnimatorCompat animation) { 2390 if (!mEnded) { 2391 mViewHolder.setIsRecyclable(true); 2392 } 2393 mEnded = true; 2394 } 2395 2396 @Override 2397 public void onAnimationCancel(ValueAnimatorCompat animation) { 2398 setFraction(1f); //make sure we recover the view's state. 2399 } 2400 2401 @Override 2402 public void onAnimationRepeat(ValueAnimatorCompat animation) { 2403 2404 } 2405 } 2406}