forked from h6ah4i/android-advancedrecyclerview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RecyclerViewDragDropManager.java
1899 lines (1553 loc) · 71.3 KB
/
RecyclerViewDragDropManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2015 Haruki Hasegawa
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.h6ah4i.android.widget.advrecyclerview.draggable;
import android.graphics.Rect;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import com.h6ah4i.android.widget.advrecyclerview.utils.CustomRecyclerViewUtils;
import com.h6ah4i.android.widget.advrecyclerview.utils.WrapperAdapterUtils;
import java.lang.ref.WeakReference;
/**
* Provides item drag & drop operation for {@link android.support.v7.widget.RecyclerView}
*/
@SuppressWarnings("PointlessBitwiseExpression")
public class RecyclerViewDragDropManager implements DraggableItemConstants {
private static final String TAG = "ARVDragDropManager";
/**
* Default interpolator used for "swap target transition"
*/
public static final Interpolator DEFAULT_SWAP_TARGET_TRANSITION_INTERPOLATOR = new BasicSwapTargetTranslationInterpolator();
/**
* Default interpolator used for "item settle back into place" animation
*/
public static final Interpolator DEFAULT_ITEM_SETTLE_BACK_INTO_PLACE_ANIMATION_INTERPOLATOR = new DecelerateInterpolator();
// ---
/**
* Used for listening item drag events
*/
public interface OnItemDragEventListener {
/**
* Callback method to be invoked when dragging is started.
*
* @param position The position of the item.
*/
void onItemDragStarted(int position);
/**
* Callback method to be invoked when item position is changed during drag.
*
* @param fromPosition The old position of the item.
* @param toPosition The new position of the item
*/
void onItemDragPositionChanged(int fromPosition, int toPosition);
/**
* Callback method to be invoked when dragging is finished.
*
* @param fromPosition Previous position of the item.
* @param toPosition New position of the item.
* @param result Indicates whether the dragging operation was succeeded.
*/
void onItemDragFinished(int fromPosition, int toPosition, boolean result);
/**
* Callback method to be invoked when the distance of currently dragging item is updated.
*
* @param offsetX The horizontal distance of currently dragging item from the initial position in pixels.
* @param offsetY The vertical distance of currently dragging item from the initial position in pixels.
*/
void onItemDragMoveDistanceUpdated(int offsetX, int offsetY);
}
// --
private static final int SCROLL_DIR_NONE = 0;
private static final int SCROLL_DIR_UP = (1 << 0);
private static final int SCROLL_DIR_DOWN = (1 << 1);
private static final int SCROLL_DIR_LEFT = (1 << 2);
private static final int SCROLL_DIR_RIGHT = (1 << 3);
private static final boolean LOCAL_LOGV = false;
private static final boolean LOCAL_LOGD = false;
private static final float SCROLL_THRESHOLD = 0.3f; // 0.0f < X < 0.5f
private static final float SCROLL_AMOUNT_COEFF = 25;
private static final float SCROLL_TOUCH_SLOP_MULTIPLY = 1.5f;
static class SwapTarget {
public RecyclerView.ViewHolder holder;
public int position;
public boolean self;
public void clear() {
holder = null;
position = RecyclerView.NO_POSITION;
self = false;
}
}
private RecyclerView mRecyclerView;
private Interpolator mSwapTargetTranslationInterpolator = DEFAULT_SWAP_TARGET_TRANSITION_INTERPOLATOR;
private ScrollOnDraggingProcessRunnable mScrollOnDraggingProcess;
private RecyclerView.OnItemTouchListener mInternalUseOnItemTouchListener;
private RecyclerView.OnScrollListener mInternalUseOnScrollListener;
private BaseEdgeEffectDecorator mEdgeEffectDecorator;
private NinePatchDrawable mShadowDrawable;
private float mDisplayDensity;
private int mTouchSlop;
private int mScrollTouchSlop;
private int mInitialTouchX;
private int mInitialTouchY;
private long mInitialTouchItemId = RecyclerView.NO_ID;
private boolean mInitiateOnLongPress;
private boolean mInitiateOnMove = true;
private int mLongPressTimeout;
private boolean mCheckCanDrop;
private boolean mInScrollByMethod;
private int mActualScrollByXAmount;
private int mActualScrollByYAmount;
private final Rect mTmpRect1 = new Rect();
private int mItemSettleBackIntoPlaceAnimationDuration = 200;
private Interpolator mItemSettleBackIntoPlaceAnimationInterpolator = DEFAULT_ITEM_SETTLE_BACK_INTO_PLACE_ANIMATION_INTERPOLATOR;
// these fields are only valid while dragging
private DraggableItemWrapperAdapter mAdapter;
/*package*/ RecyclerView.ViewHolder mDraggingItemViewHolder;
private DraggingItemInfo mDraggingItemInfo;
private DraggingItemDecorator mDraggingItemDecorator;
private SwapTargetItemOperator mSwapTargetItemOperator;
private int mLastTouchX;
private int mLastTouchY;
private int mDragStartTouchX;
private int mDragStartTouchY;
private int mDragMinTouchX;
private int mDragMinTouchY;
private int mDragMaxTouchX;
private int mDragMaxTouchY;
private int mDragScrollDistanceX;
private int mDragScrollDistanceY;
private int mScrollDirMask = SCROLL_DIR_NONE;
private int mOrigOverScrollMode;
private ItemDraggableRange mDraggableRange;
private InternalHandler mHandler;
private OnItemDragEventListener mItemDragEventListener;
private boolean mCanDragH;
private boolean mCanDragV;
private float mDragEdgeScrollSpeed = 1.0f;
private SwapTarget mTempSwapTarget = new SwapTarget();
/**
* Constructor.
*/
public RecyclerViewDragDropManager() {
mInternalUseOnItemTouchListener = new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
return RecyclerViewDragDropManager.this.onInterceptTouchEvent(rv, e);
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
RecyclerViewDragDropManager.this.onTouchEvent(rv, e);
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
RecyclerViewDragDropManager.this.onRequestDisallowInterceptTouchEvent(disallowIntercept);
}
};
mInternalUseOnScrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
RecyclerViewDragDropManager.this.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
RecyclerViewDragDropManager.this.onScrolled(recyclerView, dx, dy);
}
};
mScrollOnDraggingProcess = new ScrollOnDraggingProcessRunnable(this);
mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
}
/**
* Create wrapped adapter.
*
* @param adapter The target adapter.
* @return Wrapped adapter which is associated to this {@link RecyclerViewDragDropManager} instance.
*/
@SuppressWarnings("unchecked")
public RecyclerView.Adapter createWrappedAdapter(@NonNull RecyclerView.Adapter adapter) {
if (!adapter.hasStableIds()) {
throw new IllegalArgumentException("The passed adapter does not support stable IDs");
}
if (mAdapter != null) {
throw new IllegalStateException("already have a wrapped adapter");
}
mAdapter = new DraggableItemWrapperAdapter(this, adapter);
return mAdapter;
}
/**
* Indicates this manager instance has released or not.
*
* @return True if this manager instance has released
*/
public boolean isReleased() {
return (mInternalUseOnItemTouchListener == null);
}
/**
* <p>Attaches {@link android.support.v7.widget.RecyclerView} instance.</p>
* <p>Before calling this method, the target {@link android.support.v7.widget.RecyclerView} must set
* the wrapped adapter instance which is returned by the
* {@link #createWrappedAdapter(android.support.v7.widget.RecyclerView.Adapter)} method.</p>
*
* @param rv The {@link android.support.v7.widget.RecyclerView} instance
*/
public void attachRecyclerView(@NonNull RecyclerView rv) {
if (isReleased()) {
throw new IllegalStateException("Accessing released object");
}
if (mRecyclerView != null) {
throw new IllegalStateException("RecyclerView instance has already been set");
}
if (mAdapter == null || getDraggableItemWrapperAdapter(rv) != mAdapter) {
throw new IllegalStateException("adapter is not set properly");
}
mRecyclerView = rv;
mRecyclerView.addOnScrollListener(mInternalUseOnScrollListener);
mRecyclerView.addOnItemTouchListener(mInternalUseOnItemTouchListener);
mDisplayDensity = mRecyclerView.getResources().getDisplayMetrics().density;
mTouchSlop = ViewConfiguration.get(mRecyclerView.getContext()).getScaledTouchSlop();
mScrollTouchSlop = (int) (mTouchSlop * SCROLL_TOUCH_SLOP_MULTIPLY + 0.5f);
mHandler = new InternalHandler(this);
if (supportsEdgeEffect()) {
// edge effect is available on ICS or later
switch (CustomRecyclerViewUtils.getOrientation(mRecyclerView)) {
case CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL:
mEdgeEffectDecorator = new LeftRightEdgeEffectDecorator(mRecyclerView);
break;
case CustomRecyclerViewUtils.ORIENTATION_VERTICAL:
mEdgeEffectDecorator = new TopBottomEdgeEffectDecorator(mRecyclerView);
break;
}
if (mEdgeEffectDecorator != null) {
mEdgeEffectDecorator.start();
}
}
}
/**
* <p>Detach the {@link android.support.v7.widget.RecyclerView} instance and release internal field references.</p>
* <p>This method should be called in order to avoid memory leaks.</p>
*/
public void release() {
cancelDrag(true);
if (mHandler != null) {
mHandler.release();
mHandler = null;
}
if (mEdgeEffectDecorator != null) {
mEdgeEffectDecorator.finish();
mEdgeEffectDecorator = null;
}
if (mRecyclerView != null && mInternalUseOnItemTouchListener != null) {
mRecyclerView.removeOnItemTouchListener(mInternalUseOnItemTouchListener);
}
mInternalUseOnItemTouchListener = null;
if (mRecyclerView != null && mInternalUseOnScrollListener != null) {
mRecyclerView.removeOnScrollListener(mInternalUseOnScrollListener);
}
mInternalUseOnScrollListener = null;
if (mScrollOnDraggingProcess != null) {
mScrollOnDraggingProcess.release();
mScrollOnDraggingProcess = null;
}
mAdapter = null;
mRecyclerView = null;
mSwapTargetTranslationInterpolator = null;
}
/**
* Indicates whether currently performing item dragging.
*
* @return True if currently performing item dragging
*/
public boolean isDragging() {
return (mDraggingItemInfo != null) && (!mHandler.isCancelDragRequested());
}
/**
* Sets 9-patch image which is used for the actively dragging item
*
* @param drawable The 9-patch drawable
*/
public void setDraggingItemShadowDrawable(@Nullable NinePatchDrawable drawable) {
mShadowDrawable = drawable;
}
/**
* Sets the interpolator which is used for determining the position of the swapping item.
*
* @param interpolator Interpolator to set or null to clear
*/
public void setSwapTargetTranslationInterpolator(@Nullable Interpolator interpolator) {
mSwapTargetTranslationInterpolator = interpolator;
}
/**
* Returns whether dragging starts on a long press or not.
*
* @return True if dragging starts on a long press, false otherwise.
*/
public boolean isInitiateOnLongPressEnabled() {
return mInitiateOnLongPress;
}
/**
* Sets whether dragging starts on a long press. (default: false)
*
* @param initiateOnLongPress True to initiate dragging on long press.
*/
public void setInitiateOnLongPress(boolean initiateOnLongPress) {
mInitiateOnLongPress = initiateOnLongPress;
}
/**
* Returns whether dragging starts on move motions.
*
* @return True if dragging starts on move motions, false otherwise.
*/
public boolean isInitiateOnMoveEnabled() {
return mInitiateOnMove;
}
/**
* Sets whether dragging starts on move motions. (default: true)
*
* @param initiateOnMove True to initiate dragging on move motions.
*/
public void setInitiateOnMove(boolean initiateOnMove) {
mInitiateOnMove = initiateOnMove;
}
/**
* Sets the time required to consider press as long press. (default: 500ms)
*
* @param longPressTimeout Integer in milli seconds.
*/
public void setLongPressTimeout(int longPressTimeout) {
mLongPressTimeout = longPressTimeout;
}
/**
* Gets the interpolator which ise used for determining the position of the swapping item.
*
* @return Interpolator which is used for determining the position of the swapping item
*/
public Interpolator setSwapTargetTranslationInterpolator() {
return mSwapTargetTranslationInterpolator;
}
/**
* Gets OnItemDragEventListener listener
*
* @return The listener object
*/
public
@Nullable
OnItemDragEventListener getOnItemDragEventListener() {
return mItemDragEventListener;
}
/**
* Sets OnItemDragEventListener listener
*
* @param listener The listener object
*/
public void setOnItemDragEventListener(@Nullable OnItemDragEventListener listener) {
mItemDragEventListener = listener;
}
/**
* Sets drag edge scroll speed.
*
* @param speed The coefficient value of drag edge scrolling speed. (valid range: 0.0f .. 2.0)
*/
public void setDragEdgeScrollSpeed(float speed) {
mDragEdgeScrollSpeed = Math.min(Math.max(speed, 0.0f), 2.0f);
}
/**
* Gets drag edge scroll speed.
*
* @return The coefficient value of drag edges scrolling speed.
*/
public float getDragEdgeScrollSpeed() {
return mDragEdgeScrollSpeed;
}
/**
* Sets whether to use {@link DraggableItemAdapter#onCheckCanDrop(int, int)}.
*
* @param enabled True if use {@link DraggableItemAdapter#onCheckCanDrop(int, int)}.
*/
public void setCheckCanDropEnabled(boolean enabled) {
mCheckCanDrop = enabled;
}
/**
* Gets whether to use {@link DraggableItemAdapter#onCheckCanDrop(int, int)}.
*
* @return True if {@link DraggableItemAdapter#onCheckCanDrop(int, int)} is used, false otherwise.
*/
public boolean isCheckCanDropEnabled() {
return mCheckCanDrop;
}
/*package*/ boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
final int action = MotionEventCompat.getActionMasked(e);
if (LOCAL_LOGV) {
Log.v(TAG, "onInterceptTouchEvent() action = " + action);
}
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handleActionUpOrCancel(action, true);
break;
case MotionEvent.ACTION_DOWN:
if (!isDragging()) {
handleActionDown(rv, e);
}
break;
case MotionEvent.ACTION_MOVE:
if (isDragging()) {
// NOTE: The first ACTION_MOVE event will come here. (maybe a bug of RecyclerView?)
handleActionMoveWhileDragging(rv, e);
return true;
} else {
if (handleActionMoveWhileNotDragging(rv, e)) {
return true;
}
}
}
return false;
}
/*package*/ void onTouchEvent(RecyclerView rv, MotionEvent e) {
final int action = MotionEventCompat.getActionMasked(e);
if (LOCAL_LOGV) {
Log.v(TAG, "onTouchEvent() action = " + action);
}
if (!isDragging()) {
// Log.w(TAG, "onTouchEvent() - unexpected state");
return;
}
switch (action) {
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
handleActionUpOrCancel(action, true);
break;
case MotionEvent.ACTION_MOVE:
handleActionMoveWhileDragging(rv, e);
break;
}
}
/*package */ void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (disallowIntercept) {
cancelDrag(true);
}
}
/*package*/ void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (LOCAL_LOGV) {
Log.v(TAG, "onScrolled(dx = " + dx + ", dy = " + dy + ")");
}
if (mInScrollByMethod) {
mActualScrollByXAmount = dx;
mActualScrollByYAmount = dy;
} else if (isDragging()) {
ViewCompat.postOnAnimationDelayed(mRecyclerView, mCheckItemSwappingRunnable, 500);
}
}
/*package*/ void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (LOCAL_LOGV) {
Log.v(TAG, "onScrollStateChanged(newState = " + newState + ")");
}
if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
cancelDrag(true);
}
}
private boolean handleActionDown(RecyclerView rv, MotionEvent e) {
final RecyclerView.ViewHolder holder = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, e.getX(), e.getY());
if (!checkTouchedItemState(rv, holder)) {
return false;
}
final int orientation = CustomRecyclerViewUtils.getOrientation(mRecyclerView);
final int spanCount = CustomRecyclerViewUtils.getSpanCount(mRecyclerView);
mInitialTouchX = mLastTouchX = (int) (e.getX() + 0.5f);
mInitialTouchY = mLastTouchY = (int) (e.getY() + 0.5f);
mInitialTouchItemId = holder.getItemId();
mCanDragH = (orientation == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) ||
((orientation == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) && (spanCount > 1));
mCanDragV = (orientation == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) ||
((orientation == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) && (spanCount > 1));
if (mInitiateOnLongPress) {
mHandler.startLongPressDetection(e, mLongPressTimeout);
}
return true;
}
/*package*/ void handleOnLongPress(MotionEvent e) {
if (mInitiateOnLongPress) {
checkConditionAndStartDragging(mRecyclerView, e, false);
}
}
@SuppressWarnings("unchecked")
private void startDragging(RecyclerView rv, MotionEvent e, RecyclerView.ViewHolder holder, ItemDraggableRange range) {
safeEndAnimation(rv, holder);
mHandler.cancelLongPressDetection();
mDraggingItemInfo = new DraggingItemInfo(rv, holder, mLastTouchX, mLastTouchY);
mDraggingItemViewHolder = holder;
// XXX if setIsRecyclable() is used, another view holder objects will be created
// which has the same ID with currently dragging item... Not works as expected.
// holder.setIsRecyclable(false);
mDraggableRange = range;
mOrigOverScrollMode = ViewCompat.getOverScrollMode(rv);
ViewCompat.setOverScrollMode(rv, ViewCompat.OVER_SCROLL_NEVER);
mLastTouchX = (int) (e.getX() + 0.5f);
mLastTouchY = (int) (e.getY() + 0.5f);
// disable auto scrolling until user moves the item
mDragStartTouchY = mDragMinTouchY = mDragMaxTouchY = mLastTouchY;
mDragStartTouchX = mDragMinTouchX = mDragMaxTouchX = mLastTouchX;
mScrollDirMask = SCROLL_DIR_NONE;
mRecyclerView.getParent().requestDisallowInterceptTouchEvent(true);
startScrollOnDraggingProcess();
// raise onDragItemStarted() event
mAdapter.onDragItemStarted(mDraggingItemInfo, holder, mDraggableRange);
// setup decorators
mAdapter.onBindViewHolder(holder, holder.getLayoutPosition());
mDraggingItemDecorator = new DraggingItemDecorator(mRecyclerView, holder, mDraggableRange);
mDraggingItemDecorator.setShadowDrawable(mShadowDrawable);
mDraggingItemDecorator.start(e, mDraggingItemInfo);
final int layoutType = CustomRecyclerViewUtils.getLayoutType(mRecyclerView);
if (supportsViewTranslation() && !mCheckCanDrop &&
(layoutType == CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_VERTICAL ||
layoutType == CustomRecyclerViewUtils.LAYOUT_TYPE_LINEAR_HORIZONTAL)) {
mSwapTargetItemOperator = new SwapTargetItemOperator(mRecyclerView, holder, mDraggableRange, mDraggingItemInfo);
mSwapTargetItemOperator.setSwapTargetTranslationInterpolator(mSwapTargetTranslationInterpolator);
mSwapTargetItemOperator.start();
mSwapTargetItemOperator.update(mDraggingItemDecorator.getDraggingItemTranslationX(), mDraggingItemDecorator.getDraggingItemTranslationY());
}
if (mEdgeEffectDecorator != null) {
mEdgeEffectDecorator.reorderToTop();
}
if (mItemDragEventListener != null) {
mItemDragEventListener.onItemDragStarted(mAdapter.getDraggingItemInitialPosition());
mItemDragEventListener.onItemDragMoveDistanceUpdated(0, 0);
}
}
/**
* Cancel dragging.
*/
public void cancelDrag() {
cancelDrag(false);
}
/*package*/ void cancelDrag(boolean immediately) {
handleActionUpOrCancel(MotionEvent.ACTION_CANCEL, false);
if (immediately) {
finishDragging(false);
} else {
if (isDragging()) {
mHandler.requestDeferredCancelDrag();
}
}
}
private void finishDragging(boolean result) {
// RecyclerView.ViewHolder draggedItem = mDraggingItemViewHolder;
if (!isDragging()) {
return;
}
// cancel deferred request
if (mHandler != null) {
mHandler.removeDeferredCancelDragRequest();
}
// NOTE: setOverScrollMode() have to be called before calling removeItemDecoration()
if (mRecyclerView != null && mDraggingItemViewHolder != null) {
ViewCompat.setOverScrollMode(mRecyclerView, mOrigOverScrollMode);
}
if (mDraggingItemDecorator != null) {
mDraggingItemDecorator.setReturnToDefaultPositionAnimationDuration(mItemSettleBackIntoPlaceAnimationDuration);
mDraggingItemDecorator.setReturnToDefaultPositionAnimationInterpolator(mItemSettleBackIntoPlaceAnimationInterpolator);
mDraggingItemDecorator.finish(true);
}
if (mSwapTargetItemOperator != null) {
mSwapTargetItemOperator.setReturnToDefaultPositionAnimationDuration(mItemSettleBackIntoPlaceAnimationDuration);
mDraggingItemDecorator.setReturnToDefaultPositionAnimationInterpolator(mItemSettleBackIntoPlaceAnimationInterpolator);
mSwapTargetItemOperator.finish(true);
}
if (mEdgeEffectDecorator != null) {
mEdgeEffectDecorator.releaseBothGlows();
}
stopScrollOnDraggingProcess();
if (mRecyclerView != null && mRecyclerView.getParent() != null) {
mRecyclerView.getParent().requestDisallowInterceptTouchEvent(false);
}
if (mRecyclerView != null) {
mRecyclerView.invalidate();
}
mDraggableRange = null;
mDraggingItemDecorator = null;
mSwapTargetItemOperator = null;
mDraggingItemViewHolder = null;
mDraggingItemInfo = null;
mLastTouchX = 0;
mLastTouchY = 0;
mDragStartTouchX = 0;
mDragStartTouchY = 0;
mDragMinTouchX = 0;
mDragMinTouchY = 0;
mDragMaxTouchX = 0;
mDragMaxTouchY = 0;
mDragScrollDistanceX = 0;
mDragScrollDistanceY = 0;
mCanDragH = false;
mCanDragV = false;
int draggingItemInitialPosition = RecyclerView.NO_POSITION;
int draggingItemCurrentPosition = RecyclerView.NO_POSITION;
// raise onDragItemFinished() event
if (mAdapter != null) {
draggingItemInitialPosition = mAdapter.getDraggingItemInitialPosition();
draggingItemCurrentPosition = mAdapter.getDraggingItemCurrentPosition();
mAdapter.onDragItemFinished(result);
}
// if (draggedItem != null) {
// draggedItem.setIsRecyclable(true);
// }
if (mItemDragEventListener != null) {
mItemDragEventListener.onItemDragFinished(
draggingItemInitialPosition,
draggingItemCurrentPosition,
result);
}
}
private boolean handleActionUpOrCancel(int action, boolean invokeFinish) {
final boolean result = (action == MotionEvent.ACTION_UP);
if (mHandler != null) {
mHandler.cancelLongPressDetection();
}
mInitialTouchX = 0;
mInitialTouchY = 0;
mLastTouchX = 0;
mLastTouchY = 0;
mDragStartTouchX = 0;
mDragStartTouchY = 0;
mDragMinTouchX = 0;
mDragMinTouchY = 0;
mDragMaxTouchX = 0;
mDragMaxTouchY = 0;
mDragScrollDistanceX = 0;
mDragScrollDistanceY = 0;
mInitialTouchItemId = RecyclerView.NO_ID;
mCanDragH = false;
mCanDragV = false;
if (invokeFinish && isDragging()) {
if (LOCAL_LOGD) {
Log.d(TAG, "dragging finished --- result = " + result);
}
finishDragging(result);
}
return true;
}
private boolean handleActionMoveWhileNotDragging(RecyclerView rv, MotionEvent e) {
if (mInitiateOnMove) {
return checkConditionAndStartDragging(rv, e, true);
} else {
return false;
}
}
private boolean checkConditionAndStartDragging(RecyclerView rv, MotionEvent e, boolean checkTouchSlop) {
if (mDraggingItemInfo != null) {
return false;
}
final int touchX = (int) (e.getX() + 0.5f);
final int touchY = (int) (e.getY() + 0.5f);
mLastTouchX = touchX;
mLastTouchY = touchY;
if (mInitialTouchItemId == RecyclerView.NO_ID) {
return false;
}
if (checkTouchSlop) {
if (!((mCanDragH && (Math.abs(touchX - mInitialTouchX) > mTouchSlop)) ||
(mCanDragV && (Math.abs(touchY - mInitialTouchY) > mTouchSlop)))) {
return false;
}
}
final RecyclerView.ViewHolder holder = CustomRecyclerViewUtils.findChildViewHolderUnderWithoutTranslation(rv, mInitialTouchX, mInitialTouchY);
if (holder == null) {
return false;
}
int position = CustomRecyclerViewUtils.getSynchronizedPosition(holder);
if (position == RecyclerView.NO_POSITION) {
return false;
}
final View view = holder.itemView;
final int translateX = (int) (ViewCompat.getTranslationX(view) + 0.5f);
final int translateY = (int) (ViewCompat.getTranslationY(view) + 0.5f);
final int viewX = touchX - (view.getLeft() + translateX);
final int viewY = touchY - (view.getTop() + translateY);
if (!mAdapter.canStartDrag(holder, position, viewX, viewY)) {
return false;
}
ItemDraggableRange range = mAdapter.getItemDraggableRange(holder, position);
if (range == null) {
range = new ItemDraggableRange(0, Math.max(0, mAdapter.getItemCount() - 1));
}
verifyItemDraggableRange(range, holder);
if (LOCAL_LOGD) {
Log.d(TAG, "dragging started");
}
startDragging(rv, e, holder, range);
return true;
}
private void verifyItemDraggableRange(ItemDraggableRange range, RecyclerView.ViewHolder holder) {
final int start = 0;
final int end = Math.max(0, mAdapter.getItemCount() - 1);
if (range.getStart() > range.getEnd()) {
throw new IllegalStateException("Invalid range specified --- start > range (range = " + range + ")");
}
if (range.getStart() < start) {
throw new IllegalStateException("Invalid range specified --- start < 0 (range = " + range + ")");
}
if (range.getEnd() > end) {
throw new IllegalStateException("Invalid range specified --- end >= count (range = " + range + ")");
}
if (!range.checkInRange(holder.getAdapterPosition())) {
throw new IllegalStateException(
"Invalid range specified --- does not contain drag target item"
+ " (range = " + range + ", position = " + holder.getAdapterPosition() + ")");
}
}
private void handleActionMoveWhileDragging(RecyclerView rv, MotionEvent e) {
mLastTouchX = (int) (e.getX() + 0.5f);
mLastTouchY = (int) (e.getY() + 0.5f);
mDragMinTouchX = Math.min(mDragMinTouchX, mLastTouchX);
mDragMinTouchY = Math.min(mDragMinTouchY, mLastTouchY);
mDragMaxTouchX = Math.max(mDragMaxTouchX, mLastTouchX);
mDragMaxTouchY = Math.max(mDragMaxTouchY, mLastTouchY);
// update drag direction mask
updateDragDirectionMask();
// update decorators
final boolean updated = mDraggingItemDecorator.update(e, false);
if (updated) {
if (mSwapTargetItemOperator != null) {
mSwapTargetItemOperator.update(mDraggingItemDecorator.getDraggingItemTranslationX(), mDraggingItemDecorator.getDraggingItemTranslationY());
}
// check swapping
checkItemSwapping(rv);
onItemMoveDistanceUpdated();
}
}
private void updateDragDirectionMask() {
if (CustomRecyclerViewUtils.getOrientation(mRecyclerView) == CustomRecyclerViewUtils.ORIENTATION_VERTICAL) {
if (((mDragStartTouchY - mDragMinTouchY) > mScrollTouchSlop) ||
((mDragMaxTouchY - mLastTouchY) > mScrollTouchSlop)) {
mScrollDirMask |= SCROLL_DIR_UP;
}
if (((mDragMaxTouchY - mDragStartTouchY) > mScrollTouchSlop) ||
((mLastTouchY - mDragMinTouchY) > mScrollTouchSlop)) {
mScrollDirMask |= SCROLL_DIR_DOWN;
}
} else if (CustomRecyclerViewUtils.getOrientation(mRecyclerView) == CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL) {
if (((mDragStartTouchX - mDragMinTouchX) > mScrollTouchSlop) ||
((mDragMaxTouchX - mLastTouchX) > mScrollTouchSlop)) {
mScrollDirMask |= SCROLL_DIR_LEFT;
}
if (((mDragMaxTouchX - mDragStartTouchX) > mScrollTouchSlop) ||
((mLastTouchX - mDragMinTouchX) > mScrollTouchSlop)) {
mScrollDirMask |= SCROLL_DIR_RIGHT;
}
}
}
/*package*/ void checkItemSwapping(RecyclerView rv) {
final RecyclerView.ViewHolder draggingItem = mDraggingItemViewHolder;
final int overlayItemLeft = mLastTouchX - mDraggingItemInfo.grabbedPositionX;
final int overlayItemTop = mLastTouchY - mDraggingItemInfo.grabbedPositionY;
final int draggingItemInitialPosition = mAdapter.getDraggingItemInitialPosition();
final int draggingItemCurrentPosition = mAdapter.getDraggingItemCurrentPosition();
SwapTarget swapTarget;
boolean canSwap = false;
swapTarget = findSwapTargetItem(mTempSwapTarget, rv, draggingItem, mDraggingItemInfo, overlayItemLeft, overlayItemTop, mDraggableRange, mCheckCanDrop, false);
if (swapTarget.position != RecyclerView.NO_POSITION) {
if (!mCheckCanDrop) {
canSwap = true;
}
if (!canSwap) {
canSwap = mAdapter.canDropItems(draggingItemInitialPosition, swapTarget.position);
}
if (!canSwap) {
swapTarget = findSwapTargetItem(mTempSwapTarget, rv, draggingItem, mDraggingItemInfo, overlayItemLeft, overlayItemTop, mDraggableRange, mCheckCanDrop, true);
if (swapTarget.position != RecyclerView.NO_POSITION) {
canSwap = mAdapter.canDropItems(draggingItemInitialPosition, swapTarget.position);
}
}
}
if (canSwap) {
swapItems(rv, draggingItemCurrentPosition, draggingItem, swapTarget.holder);
}
if (mSwapTargetItemOperator != null) {
mSwapTargetItemOperator.setSwapTargetItem((canSwap) ? swapTarget.holder : null);
}
}
private void onItemMoveDistanceUpdated() {
if (mItemDragEventListener == null) {
return;
}
final int moveX = mDragScrollDistanceX + mDraggingItemDecorator.getDraggingItemMoveOffsetX();
final int moveY = mDragScrollDistanceY + mDraggingItemDecorator.getDraggingItemMoveOffsetY();
mItemDragEventListener.onItemDragMoveDistanceUpdated(moveX, moveY);
}
/*package*/ void handleScrollOnDragging() {
final RecyclerView rv = mRecyclerView;
switch (CustomRecyclerViewUtils.getOrientation(rv)) {
case CustomRecyclerViewUtils.ORIENTATION_VERTICAL:
handleScrollOnDraggingInternal(rv, false);
break;
case CustomRecyclerViewUtils.ORIENTATION_HORIZONTAL:
handleScrollOnDraggingInternal(rv, true);
break;
}
}
private void handleScrollOnDraggingInternal(RecyclerView rv, boolean horizontal) {
final int edge = (horizontal) ? rv.getWidth() : rv.getHeight();
if (edge == 0) {
return;
}