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