-
Notifications
You must be signed in to change notification settings - Fork 554
/
Copy pathFlexibleAdapter.java
5300 lines (4960 loc) · 213 KB
/
FlexibleAdapter.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 2015-2017 Davide Steduto
*
* 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 eu.davidea.flexibleadapter;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.CallSuper;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import eu.davidea.flexibleadapter.common.SmoothScrollGridLayoutManager;
import eu.davidea.flexibleadapter.common.SmoothScrollLinearLayoutManager;
import eu.davidea.flexibleadapter.helpers.ItemTouchHelperCallback;
import eu.davidea.flexibleadapter.helpers.StickyHeaderHelper;
import eu.davidea.flexibleadapter.items.IExpandable;
import eu.davidea.flexibleadapter.items.IFilterable;
import eu.davidea.flexibleadapter.items.IFlexible;
import eu.davidea.flexibleadapter.items.IHeader;
import eu.davidea.flexibleadapter.items.ISectionable;
import eu.davidea.flexibleadapter.utils.FlexibleUtils;
import eu.davidea.viewholders.ExpandableViewHolder;
import eu.davidea.viewholders.FlexibleViewHolder;
import static eu.davidea.flexibleadapter.utils.FlexibleUtils.getClassName;
/**
* This Adapter is backed by an ArrayList of arbitrary objects of class <b>T</b>, where <b>T</b>
* is your adapter object containing the data of a single item. This Adapter simplifies the
* development by providing a set of standard methods to handle changes on the data set such as:
* <i>selecting, filtering, adding, removing, moving</i> and <i>animating</i> an item.
* <p>
* With version 5.0.0, <b>T</b> item must implement {@link IFlexible} item interface as base item
* for all view types and new methods have been added in order to:
* <ul>
* <li>handle Headers/Sections with {@link IHeader} and {@link ISectionable} items;</li>
* <li>expand and collapse {@link IExpandable} items;</li>
* <li>drag&drop and swipe any items.</li>
* </ul>
*
* @author Davide Steduto
* @see AnimatorAdapter
* @see SelectableAdapter
* @see IFlexible
* @see FlexibleViewHolder
* @see ExpandableViewHolder
* @since 03/05/2015 Created
* <br>16/01/2016 Expandable items
* <br>24/01/2016 Drag&Drop, Swipe-to-dismiss
* <br>30/01/2016 Class now extends {@link AnimatorAdapter} that extends {@link SelectableAdapter}
* <br>02/02/2016 New code reorganization, new item interfaces and full refactoring
* <br>08/02/2016 Headers/Sections
* <br>10/02/2016 The class is not abstract anymore, it is ready to be used
* <br>20/02/2016 Sticky headers
* <br>22/04/2016 Endless Scrolling
* <br>13/07/2016 Update and Filter operations are executed asynchronously (high performance on big list)
* <br>25/11/2016 Scrollable Headers and Footers; Reviewed EndlessScroll
* <br>28/03/2017 Adapter now makes a copy of the provided list at startup, updateDataSet and filterItems
* <br>10/04/2017 Endless Top Scrolling
* <br>15/04/2017 Starting or resetting the Filter will empty the bin of the deletedItems
* <br>23/04/2017 Wrapper class for any third type of LayoutManagers
*/
@SuppressWarnings({"Range", "unused", "unchecked", "ConstantConditions", "SuspiciousMethodCalls", "WeakerAccess"})
public class FlexibleAdapter<T extends IFlexible>
extends AnimatorAdapter
implements ItemTouchHelperCallback.AdapterCallback {
private static final String TAG = FlexibleAdapter.class.getSimpleName();
private static final String EXTRA_PARENT = TAG + "_parentSelected";
private static final String EXTRA_CHILD = TAG + "_childSelected";
private static final String EXTRA_HEADERS = TAG + "_headersShown";
private static final String EXTRA_STICKY = TAG + "_stickyHeaders";
private static final String EXTRA_LEVEL = TAG + "_selectedLevel";
private static final String EXTRA_SEARCH = TAG + "_searchText";
/* The main container for ALL items */
private List<T> mItems, mTempItems, mOriginalList;
/* HashSet, AsyncTask and DiffUtil objects, will increase performance in big list */
private Set<T> mHashItems;
private List<Notification> mNotifications;
private FilterAsyncTask mFilterAsyncTask;
private long start, time;
/* Handler for delayed actions */
protected final int UPDATE = 1, FILTER = 2, LOAD_MORE_COMPLETE = 8;
protected Handler mHandler = new Handler(Looper.getMainLooper(), new HandlerCallback());
/* Deleted items and RestoreList (Undo) */
private List<RestoreInfo> mRestoreList;
private boolean restoreSelection = false, multiRange = false, unlinkOnRemoveHeader = false,
permanentDelete = true, adjustSelected = true;
/* Scrollable Headers/Footers items */
private List<T> mScrollableHeaders, mScrollableFooters;
/* Section items (with sticky headers) */
private boolean headersShown = false, recursive = false;
private int mStickyElevation;
private StickyHeaderHelper mStickyHeaderHelper;
private ViewGroup mStickyContainer;
/* ViewTypes */
protected LayoutInflater mInflater;
@SuppressLint("UseSparseArrays")//We can usually count Type instances on the fingers of a hand
private HashMap<Integer, T> mTypeInstances = new HashMap<>();
private boolean autoMap = false;
/* Filter */
private String mSearchText = "", mOldSearchText = "";
private Set<IExpandable> mExpandedFilterFlags;
private boolean notifyChangeOfUnfilteredItems = true, filtering = false,
notifyMoveOfFilteredItems = false;
private static int ANIMATE_TO_LIMIT = 1000;
private int mAnimateToLimit = ANIMATE_TO_LIMIT;
/* Expandable flags */
private int mMinCollapsibleLevel = 0, mSelectedLevel = -1;
private boolean scrollOnExpand = false, collapseOnExpand = false, collapseSubLevels = false,
childSelected = false, parentSelected = false;
/* Drag&Drop and Swipe helpers */
private ItemTouchHelperCallback mItemTouchHelperCallback;
private ItemTouchHelper mItemTouchHelper;
/* EndlessScroll */
private int mEndlessScrollThreshold = 1, mEndlessTargetCount = 0, mEndlessPageSize = 0;
private boolean endlessLoading = false, endlessScrollEnabled = false, mTopEndless = false;
private T mProgressItem;
/* Listeners */
public OnItemClickListener mItemClickListener;
public OnItemLongClickListener mItemLongClickListener;
protected OnUpdateListener mUpdateListener;
protected OnItemMoveListener mItemMoveListener;
protected OnItemSwipeListener mItemSwipeListener;
protected EndlessScrollListener mEndlessScrollListener;
protected OnDeleteCompleteListener mDeleteCompleteListener;
protected OnStickyHeaderChangeListener mStickyHeaderChangeListener;
/*--------------*/
/* CONSTRUCTORS */
/*--------------*/
/**
* Simple Constructor with NO listeners!
*
* @param items items to display.
* @see #FlexibleAdapter(List, Object)
* @see #FlexibleAdapter(List, Object, boolean)
* @since 4.2.0 Created
* <br>5.0.0-rc2 Copy of the Original List is done internally
*/
public FlexibleAdapter(@Nullable List<T> items) {
this(items, null);
}
/**
* Main Constructor with all managed listeners for ViewHolder and the Adapter itself.
* <p>The listener must be a single instance of a class, usually <i>Activity</i> or
* <i>Fragment</i>, where you can implement how to handle the different events.</p>
* <p><b>THE ADAPTER WORKS WITH A <u>COPY</u> OF THE ORIGINAL LIST</b>:
* {@code new ArrayList<T>(originalList);}</i></p>
*
* @param items items to display
* @param listeners can be an instance of:
* <ul>
* <li>{@link OnItemClickListener}
* <li>{@link OnItemLongClickListener}
* <li>{@link OnItemMoveListener}
* <li>{@link OnItemSwipeListener}
* <li>{@link OnStickyHeaderChangeListener}
* <li>{@link OnUpdateListener}
* </ul>
* @see #FlexibleAdapter(List)
* @see #FlexibleAdapter(List, Object, boolean)
* @see #addListener(Object)
* @since 5.0.0-b1 Created
* <br>5.0.0-rc2 Copy of the Original List is done internally
*/
public FlexibleAdapter(@Nullable List<T> items, @Nullable Object listeners) {
this(items, listeners, false);
}
/**
* Same as {@link #FlexibleAdapter(List, Object)} with possibility to set stableIds.
* <p><b>Tip:</b> Setting {@code true} allows the RecyclerView to rebind only items really
* changed after a refresh with {@link #notifyDataSetChanged()} or after swapping Adapter.
* This increases performance.<br>
* Set {@code true} only if items implement {@link Object#hashCode()} and have unique ids.
* The method {@link #setHasStableIds(boolean)} will be called.</p>
*
* @param stableIds set {@code true} if item implements {@code hashcode()} and have unique ids.
* @see #FlexibleAdapter(List)
* @see #FlexibleAdapter(List, Object)
* @see #addListener(Object)
* @since 5.0.0-b8 Created
* <br>5.0.0-rc2 Copy of the Original List is done internally
*/
public FlexibleAdapter(@Nullable List<T> items, @Nullable Object listeners, boolean stableIds) {
super(stableIds);
// Copy of the original list
if (items == null) mItems = new ArrayList<>();
else mItems = new ArrayList<>(items);
// Initialize internal lists
mScrollableHeaders = new ArrayList<>();
mScrollableFooters = new ArrayList<>();
mRestoreList = new ArrayList<>();
// Create listeners instances
addListener(listeners);
// Get notified when items are inserted or removed (it adjusts selected positions)
registerAdapterDataObserver(new AdapterDataObserver());
}
/**
* Initializes the listener(s) of this Adapter.
* <p>This method is automatically called from the Constructor.</p>
*
* @param listener the object(s) instance(s) of any listener
* @return this Adapter, so the call can be chained
* @see #removeListener(Class[])
* @since 5.0.0-b6
*/
@CallSuper
public FlexibleAdapter<T> addListener(@Nullable Object listener) {
if (listener != null) {
log.i("Setting listener class %s as:", getClassName(listener));
}
if (listener instanceof OnItemClickListener) {
log.i("- OnItemClickListener");
mItemClickListener = (OnItemClickListener) listener;
for (FlexibleViewHolder holder : getAllBoundViewHolders()) {
holder.getContentView().setOnClickListener(holder);
}
}
if (listener instanceof OnItemLongClickListener) {
log.i("- OnItemLongClickListener");
mItemLongClickListener = (OnItemLongClickListener) listener;
// Restore the event
for (FlexibleViewHolder holder : getAllBoundViewHolders()) {
holder.getContentView().setOnLongClickListener(holder);
}
}
if (listener instanceof OnItemMoveListener) {
log.i("- OnItemMoveListener");
mItemMoveListener = (OnItemMoveListener) listener;
}
if (listener instanceof OnItemSwipeListener) {
log.i("- OnItemSwipeListener");
mItemSwipeListener = (OnItemSwipeListener) listener;
}
if (listener instanceof OnDeleteCompleteListener) {
log.i("- OnDeleteCompleteListener");
mDeleteCompleteListener = (OnDeleteCompleteListener) listener;
}
if (listener instanceof OnStickyHeaderChangeListener) {
log.i("- OnStickyHeaderChangeListener");
mStickyHeaderChangeListener = (OnStickyHeaderChangeListener) listener;
}
if (listener instanceof OnUpdateListener) {
log.i("- OnUpdateListener");
mUpdateListener = (OnUpdateListener) listener;
mUpdateListener.onUpdateEmptyView(getMainItemCount());
}
return this;
}
/**
* Removes one or more listeners from this Adapter.
* <p><b>Warning:</b>
* <ul><li>In case of <i>Click</i> and <i>LongClick</i> events, it will remove also the callback
* from all bound ViewHolders too. To restore these 2 events on the current bound ViewHolders
* call {@link #addListener(Object)} providing the instance of desired listener.</li>
* <li>To remove a specific listener you have to provide the Class of the listener,
* example:
* <pre>removeListener(FlexibleAdapter.OnUpdateListener.class,
* FlexibleAdapter.OnItemLongClickListener.class);</pre></li></ul></p>
*
* @param listeners the listeners type Classes to remove from the this Adapter and/or from all bound ViewHolders
* @return this Adapter, so the call can be chained
* @see #addListener(Object)
* @since 5.0.0-rc3
*/
public final FlexibleAdapter<T> removeListener(@NonNull Class... listeners) {
if (listeners == null || listeners.length == 0) {
log.e("No listener class to remove!");
return this;
}
for (Class listener : listeners) {
if (listener == OnItemClickListener.class) {
mItemClickListener = null;
log.i("Removed OnItemClickListener");
for (FlexibleViewHolder holder : getAllBoundViewHolders()) {
holder.getContentView().setOnClickListener(null);
}
}
if (listener == OnItemLongClickListener.class) {
mItemLongClickListener = null;
log.i("Removed OnItemLongClickListener");
for (FlexibleViewHolder holder : getAllBoundViewHolders()) {
holder.getContentView().setOnLongClickListener(null);
}
}
if (listener == OnItemMoveListener.class) {
mItemMoveListener = null;
log.i("Removed OnItemMoveListener");
}
if (listener == OnItemSwipeListener.class) {
mItemSwipeListener = null;
log.i("Removed OnItemSwipeListener");
}
if (listener == OnDeleteCompleteListener.class) {
mDeleteCompleteListener = null;
log.i("Removed OnDeleteCompleteListener");
}
if (listener == OnStickyHeaderChangeListener.class) {
mStickyHeaderChangeListener = null;
log.i("Removed OnStickyHeaderChangeListener");
}
if (listener == OnUpdateListener.class) {
mUpdateListener = null;
log.i("Removed OnUpdateListener");
}
}
return this;
}
/**
* {@inheritDoc}
* <p>Attaches the {@code StickyHeaderHelper} to the RecyclerView if necessary.</p>
*
* @since 5.0.0-b6
*/
@CallSuper
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
log.v("Attached Adapter to RecyclerView");
if (headersShown && areHeadersSticky()) {
mStickyHeaderHelper.attachToRecyclerView(mRecyclerView);
}
}
/**
* {@inheritDoc}
* <p>Detaches the {@code StickyHeaderHelper} from the RecyclerView if necessary.</p>
*
* @since 5.0.0-b6
*/
@CallSuper
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
if (areHeadersSticky()) {
mStickyHeaderHelper.detachFromRecyclerView();
mStickyHeaderHelper = null;
}
super.onDetachedFromRecyclerView(recyclerView);
log.v("Detached Adapter from RecyclerView");
}
/**
* Maps and expands items that are initially configured to be shown as expanded.
* <p>This method should be called during the creation of the Activity/Fragment, useful also
* after a screen rotation.</p>
*
* @return this Adapter, so the call can be chained
* @since 5.0.0-b6
*/
public FlexibleAdapter<T> expandItemsAtStartUp() {
int position = 0;
setScrollAnimate(true);
multiRange = true;
while (position < getItemCount()) {
T item = getItem(position);
if (!headersShown && isHeader(item) && !item.isHidden()) {
headersShown = true;
}
if (isExpanded(item)) {
expand(position, false, true, false);
}
position++; //+1 Check also subItems with expanded = true
}
multiRange = false;
setScrollAnimate(false);
return this;
}
/*------------------------------*/
/* SELECTION METHODS OVERRIDDEN */
/*------------------------------*/
/**
* Checks if the current item has the property {@code enabled = true}.
* <p>When an item is disabled, user cannot interact with it.</p>
*
* @param position the current position of the item to check
* @return true if the item property <i>enabled</i> is set true, false otherwise
* @since 5.0.0-b6
*/
public boolean isEnabled(int position) {
T item = getItem(position);
return item != null && item.isEnabled();
}
/**
* {@inheritDoc}
*
* @since 5.0.0-b6
*/
@Override
public boolean isSelectable(int position) {
T item = getItem(position);
return item != null && item.isSelectable();
}
/**
* {@inheritDoc}
*
* @param position position of the item to toggle the selection status for.
* @since 5.0.0-b1
*/
//TODO: Review the logic of selection coherence
@Override
public void toggleSelection(@IntRange(from = 0) int position) {
T item = getItem(position);
// Allow selection only for selectable items
if (item != null && item.isSelectable()) {
IExpandable parent = getExpandableOf(item);
boolean hasParent = parent != null;
if ((isExpandable(item) || !hasParent) && !childSelected) {
// Allow selection of Parent if no Child has been previously selected
parentSelected = true;
if (hasParent) mSelectedLevel = parent.getExpansionLevel();
super.toggleSelection(position);
} else if (hasParent && (mSelectedLevel == -1 || !parentSelected && parent.getExpansionLevel() + 1 == mSelectedLevel)) {
// Allow selection of Child of same level and if no Parent has been previously selected
childSelected = true;
mSelectedLevel = parent.getExpansionLevel() + 1;
super.toggleSelection(position);
}
}
// Reset flags if necessary, just to be sure
if (super.getSelectedItemCount() == 0) {
mSelectedLevel = -1;
parentSelected = childSelected = false;
}
}
/**
* Helper to automatically select all the items of the viewType equal to the viewType of
* the first selected item.
* <p>Examples:
* <ul><li>if user initially selects an expandable of type A, then only expandable items of
* type A can be selected.</li>
* <li>if user initially selects a non-expandable of type B, then only items of type B
* can be selected.</li>
* <li>The developer can override this behaviour by passing a list of viewTypes for which
* he wants to force the selection.</li></ul></p>
*
* @param viewTypes All the desired viewTypes to be selected, providing no view types, will
* automatically select all the viewTypes of the first item user has selected
* @since 5.0.0-b1
*/
@Override
public void selectAll(Integer... viewTypes) {
if (getSelectedItemCount() > 0 && viewTypes.length == 0) {
super.selectAll(getItemViewType(getSelectedPositions().get(0))); //Priority on the first item
} else {
super.selectAll(viewTypes); //Force the selection for the viewTypes passed
}
}
/**
* {@inheritDoc}
*
* @since 5.0.0-b1
*/
@Override
@CallSuper
public void clearSelection() {
parentSelected = childSelected = false;
super.clearSelection();
}
/**
* @return true if a parent is selected
* @since 5.0.0-b1
*/
public boolean isAnyParentSelected() {
return parentSelected;
}
/**
* @return true if any child of any parent is selected, false otherwise
* @since 5.0.0-b1
*/
public boolean isAnyChildSelected() {
return childSelected;
}
/*--------------*/
/* MAIN METHODS */
/*--------------*/
/**
* Convenience method of {@link #updateDataSet(List, boolean)} (You should read the comments
* of this method).
* <p>In this call, changes will NOT be animated: <b>Warning!</b>
* {@link #notifyDataSetChanged()} will be invoked.</p>
*
* @param items the new data set
* @see #updateDataSet(List, boolean)
* @since 5.0.0-b1 Created
* <br>5.0.0-rc2 Copy of the Original List done internally
*/
@CallSuper
public void updateDataSet(@Nullable List<T> items) {
updateDataSet(items, false);
}
/**
* This method will refresh the entire data set content. Optionally, all changes can be
* animated, limited by the value previously set with {@link #setAnimateToLimit(int)}
* to improve performance on very big list. Should provide {@code animate=false} to
* directly invoke {@link #notifyDataSetChanged()} without any animations, if {@code stableIds}
* is not set!
* <p><b>Note:</b>
* <ul><li>Scrollable Headers and Footers (if existent) will be restored in this call.</li>
* <li>I strongly recommend to implement {@link Object#hashCode()} to all adapter items
* along with {@link Object#equals(Object)}: This Adapter is making use of HashSet to
* improve performance.</li>
* </ul></p>
* <b>Note:</b> The following methods will be also called at the end of the operation:
* <ol><li>{@link #expandItemsAtStartUp()}</li>
* <li>{@link #showAllHeaders()} if headers are shown</li>
* <li>{@link #onPostUpdate()}</li>
* <li>{@link OnUpdateListener#onUpdateEmptyView(int)} if the listener is set</li></ol>
*
* @param items the new data set
* @param animate true to animate the changes, false for an instant refresh
* @see #updateDataSet(List)
* @see #setAnimateToLimit(int)
* @see #onPostUpdate()
* @since 5.0.0-b7 Created
* <br>5.0.0-b8 Synchronization animations limit
* <br>5.0.0-rc2 Copy of the Original List done internally
*/
@CallSuper
public void updateDataSet(@Nullable List<T> items, boolean animate) {
mOriginalList = null; // Reset original list from filter
if (items == null) items = new ArrayList<>();
if (animate) {
mHandler.removeMessages(UPDATE);
mHandler.sendMessage(Message.obtain(mHandler, UPDATE, items));
} else {
// Copy of the original list
List<T> newItems = new ArrayList<>(items);
prepareItemsForUpdate(newItems);
mItems = newItems;
// Execute instant reset on init
log.w("updateDataSet with notifyDataSetChanged!");
notifyDataSetChanged();
onPostUpdate();
}
}
/**
* Returns the object of type <b>T</b>.
* <p>This method cannot be overridden since the entire library relies on it.</p>
*
* @param position the position of the item in the list
* @return The <b>T</b> object for the position provided or null if item not found
* @since 1.0.0
*/
@Nullable
public T getItem(int position) {
if (position < 0 || position >= getItemCount()) return null;
return mItems.get(position);
}
/**
* This method is mostly used by the adapter if items have stableIds.
*
* @param position the position of the current item
* @return Hashcode of the item at the specific position
* @since 5.0.0-b1
*/
@Override
public long getItemId(int position) {
T item = getItem(position);
return item != null ? item.hashCode() : RecyclerView.NO_ID;
}
/**
* Returns the total number of items in the data set held by the adapter (headers and footers
* INCLUDED). Use {@link #getMainItemCount()} with {@code false} as parameter to retrieve
* only real items excluding headers and footers.
* <p><b>Note:</b> This method cannot be overridden since the selection and the internal
* methods rely on it.</p>
*
* @return the total number of items (headers and footers INCLUDED) held by the adapter
* @see #getMainItemCount()
* @see #getItemCountOfTypes(Integer...)
* @see #isEmpty()
* @since 1.0.0
*/
@Override
public int getItemCount() {
return mItems.size();
}
/**
* Returns the total number of items in the data set held by the adapter.
* <ul>
* <li>Provide {@code true} (default behavior) to count all items, same result of {@link #getItemCount()}.</li>
* <li>Provide {@code false} to count only main items (headers and footers are EXCLUDED).</li>
* </ul>
* <b>Note:</b> This method cannot be overridden since internal methods rely on it.
*
* @return the total number of items held by the adapter, with or without headers and footers,
* depending by the provided parameter
* @see #getItemCount()
* @see #getItemCountOfTypes(Integer...)
* @since 5.0.0-rc1
*/
public final int getMainItemCount() {
return hasSearchText() ? getItemCount() : getItemCount() - mScrollableHeaders.size() - mScrollableFooters.size();
}
/**
* Provides the number of items currently displayed of one or more certain types.
*
* @param viewTypes the viewTypes to count
* @return number of the viewTypes counted
* @see #getItemCount()
* @see #getMainItemCount()
* @see #isEmpty()
* @since 5.0.0-b1
*/
public final int getItemCountOfTypes(Integer... viewTypes) {
List<Integer> viewTypeList = Arrays.asList(viewTypes);
int count = 0;
for (int i = 0; i < getItemCount(); i++) {
if (viewTypeList.contains(getItemViewType(i)))
count++;
}
return count;
}
/**
* Gets an unmodifiable view of the internal list of items.
*
* @return an unmodifiable view of the current adapter list
* @since 5.0.0-rc2
*/
@NonNull
public final List<T> getCurrentItems() {
return Collections.unmodifiableList(mItems);
}
/**
* You can override this method to define your own concept of "Empty". This method is never
* called internally.
*
* @return true if the list is empty, false otherwise
* @see #getItemCount()
* @see #getItemCountOfTypes(Integer...)
* @since 4.2.0
*/
public boolean isEmpty() {
return getItemCount() == 0;
}
/**
* Retrieves the global position of the item in the Adapter list.
* If no scrollable Headers are added, the global position coincides with the cardinal position.
* <p>This method cannot be overridden since the entire library relies on it.</p>
*
* @param item the item to find
* @return the global position in the Adapter if found, -1 otherwise
* @since 5.0.0-b1
*/
public final int getGlobalPositionOf(IFlexible item) {
return item != null ? mItems.indexOf(item) : -1;
}
/**
* Retrieves the position of the Main item in the Adapter list excluding the scrollable Headers.
* If no scrollable Headers are added, the cardinal position coincides with the global position.
* <p><b>Note:</b>
* <br>- This method is NOT suitable to call when managing items: ALL insert, remove, move and
* swap operations, should done with global position {@link #getGlobalPositionOf(IFlexible)}.
* <br>- This method cannot be overridden.</p>
*
* @param item the item to find
* @return the position in the Adapter excluding the Scrollable Headers, -1 otherwise
* @since 5.0.0-rc1
*/
public final int getCardinalPositionOf(@NonNull IFlexible item) {
int position = getGlobalPositionOf(item);
if (position > mScrollableHeaders.size()) position -= mScrollableHeaders.size();
return position;
}
/**
* This method is never called internally.
*
* @param item the item to find
* @return true if the provided item is currently displayed, false otherwise
* @since 2.0.0
*/
public boolean contains(@Nullable T item) {
return item != null && mItems.contains(item);
}
/**
* New method to extract the new position where the item should lay.
* <p><b>Note: </b>The {@code Comparator} object should be customized to support <u>all</u>
* types of items this Adapter is managing or a {@code ClassCastException} will be raised.</p>
* If the {@code Comparator} is {@code null} the returned position is 0 (first position).
*
* @param item the item to evaluate the insertion
* @param comparator the Comparator object with the logic to sort the list
* @return the position resulted from sorting with the provided Comparator
* @since 5.0.0-b7
*/
public int calculatePositionFor(@NonNull Object item, @Nullable Comparator<IFlexible> comparator) {
// There's nothing to compare
if (comparator == null) return 0;
// Header is visible
if (item instanceof ISectionable) {
ISectionable sectionable = (ISectionable) item;
IHeader header = sectionable.getHeader();
if (header != null && !header.isHidden()) {
List<ISectionable> sortedList = getSectionItems(header);
sortedList.add(sectionable);
Collections.sort(sortedList, comparator);
int itemPosition = getGlobalPositionOf(sectionable);
int headerPosition = getGlobalPositionOf(header);
// #143 - calculatePositionFor() missing a +1 when addItem (fixed by condition: itemPosition != -1)
// fix represents the situation when item is before the target position (used in moveItem)
int fix = itemPosition != -1 && itemPosition < headerPosition ? 0 : 1;
int result = headerPosition + sortedList.indexOf(item) + fix;
log.v("Calculated finalPosition=%s sectionPosition=%s relativePosition=%s fix=%s",
result, headerPosition, sortedList.indexOf(item), fix);
return result;
}
}
// All other cases
List sortedList = new ArrayList<>(mItems);
if (!sortedList.contains(item)) sortedList.add(item);
Collections.sort(sortedList, comparator);
log.v("Calculated position %s for item=%s", Math.max(0, sortedList.indexOf(item)), item);
return Math.max(0, sortedList.indexOf(item));
}
/*------------------------------------*/
/* SCROLLABLE HEADERS/FOOTERS METHODS */
/*------------------------------------*/
/**
* @return unmodifiable list of Scrollable Headers currently held by the Adapter
* @see #addScrollableHeader(IFlexible)
* @see #addScrollableHeaderWithDelay(IFlexible, long, boolean)
* @since 5.0.0-rc1
*/
public final List<T> getScrollableHeaders() {
return Collections.unmodifiableList(mScrollableHeaders);
}
/**
* @return unmodifiable list of Scrollable Footers currently held by the Adapter
* @see #addScrollableFooter(IFlexible)
* @see #addScrollableFooterWithDelay(IFlexible, long, boolean)
* @since 5.0.0-rc1
*/
public final List<T> getScrollableFooters() {
return Collections.unmodifiableList(mScrollableFooters);
}
/**
* {@inheritDoc}
*/
@Override
public final boolean isScrollableHeaderOrFooter(int position) {
T item = getItem(position);
return isScrollableHeaderOrFooter(item);
}
/**
* Checks if at the provided item is a Header or Footer.
*
* @param item the item to check
* @return true if it's a scrollable item
* @since 5.0.0-rc2
*/
public final boolean isScrollableHeaderOrFooter(T item) {
return item != null && mScrollableHeaders.contains(item) || mScrollableFooters.contains(item);
}
/**
* Adds a Scrollable Header.
* <p><b>Scrollable Headers</b> have the following characteristic:
* <ul>
* <li>lay always before any main item.</li>
* <li>cannot be selectable nor draggable.</li>
* <li>cannot be inserted twice, but many can be inserted.</li>
* <li>any new header will be inserted before the existent.</li>
* <li>can be of any type so they can be bound at runtime with any data inside.</li>
* <li>won't be filtered because they won't be part of the main list, but added separately
* at the initialization phase</li>
* <li>can be added and removed with certain delay.</li>
* </ul></p>
*
* @param headerItem the header item to be added
* @return true if the header has been successfully added, false if the header already exists
* @see #getScrollableHeaders()
* @see #addScrollableHeaderWithDelay(IFlexible, long, boolean)
* @since 5.0.0-rc1
*/
public final boolean addScrollableHeader(@NonNull T headerItem) {
log.d("Add scrollable header %s", getClassName(headerItem));
if (!mScrollableHeaders.contains(headerItem)) {
headerItem.setSelectable(false);
headerItem.setDraggable(false);
int progressFix = (headerItem == mProgressItem) ? mScrollableHeaders.size() : 0;
mScrollableHeaders.add(headerItem);
setScrollAnimate(true); //Headers will scroll animate
performInsert(progressFix, Collections.singletonList(headerItem), true);
setScrollAnimate(false);
return true;
} else {
log.w("Scrollable header %s already exists", getClassName(headerItem));
return false;
}
}
/**
* Adds a Scrollable Footer.
* <p><b>Scrollable Footers</b> have the following characteristic:
* <ul>
* <li>lay always after any main item.</li>
* <li>cannot be selectable nor draggable.</li>
* <li>cannot be inserted twice, but many can be inserted.</li>
* <li>cannot scroll animate, when inserted for the first time.</li>
* <li>any new footer will be inserted after the existent.</li>
* <li>can be of any type so they can be bound at runtime with any data inside.</li>
* <li>won't be filtered because they won't be part of the main list, but added separately
* at the initialization phase</li>
* <li>can be added and removed with certain delay.</li>
* <li>endless {@code progressItem} is handled as a Scrollable Footer, but it will be always
* displayed between the main items and the others footers.</li>
* </ul></p>
*
* @param footerItem the footer item to be added
* @return true if the footer has been successfully added, false if the footer already exists
* @see #getScrollableFooters()
* @see #addScrollableFooterWithDelay(IFlexible, long, boolean)
* @since 5.0.0-rc1
*/
public final boolean addScrollableFooter(@NonNull T footerItem) {
if (!mScrollableFooters.contains(footerItem)) {
log.d("Add scrollable footer %s", getClassName(footerItem));
footerItem.setSelectable(false);
footerItem.setDraggable(false);
int progressFix = (footerItem == mProgressItem) ? mScrollableFooters.size() : 0;
//Prevent wrong position after a possible updateDataSet
if (progressFix > 0 && mScrollableFooters.size() > 0) {
mScrollableFooters.add(0, footerItem);
} else {
mScrollableFooters.add(footerItem);
}
performInsert(getItemCount() - progressFix, Collections.singletonList(footerItem), true);
return true;
} else {
log.w("Scrollable footer %s already exists", getClassName(footerItem));
return false;
}
}
/**
* Removes the provided Scrollable Header.
*
* @param headerItem the header to remove
* @see #removeScrollableHeaderWithDelay(IFlexible, long)
* @see #removeAllScrollableHeaders()
* @since 5.0.0-rc1
*/
public final void removeScrollableHeader(@NonNull T headerItem) {
if (mScrollableHeaders.remove(headerItem)) {
log.d("Remove scrollable header %s", getClassName(headerItem));
performRemove(headerItem, true);
}
}
/**
* Removes the provided Scrollable Footer.
*
* @param footerItem the footer to remove
* @see #removeScrollableFooterWithDelay(IFlexible, long)
* @see #removeAllScrollableFooters()
* @since 5.0.0-rc1
*/
public final void removeScrollableFooter(@NonNull T footerItem) {
if (mScrollableFooters.remove(footerItem)) {
log.d("Remove scrollable footer %s", getClassName(footerItem));
performRemove(footerItem, true);
}
}
/**
* Removes all Scrollable Headers at once.
*
* @see #removeScrollableHeader(IFlexible)
* @see #removeScrollableHeaderWithDelay(IFlexible, long)
* @since 5.0.0-rc1
*/
public final void removeAllScrollableHeaders() {
if (mScrollableHeaders.size() > 0) {
log.d("Remove all scrollable headers");
mItems.removeAll(mScrollableHeaders);
notifyItemRangeRemoved(0, mScrollableHeaders.size());
mScrollableHeaders.clear();
}
}
/**
* Removes all Scrollable Footers at once.
*
* @see #removeScrollableFooter(IFlexible)
* @see #removeScrollableFooterWithDelay(IFlexible, long)
* @since 5.0.0-rc1
*/
public final void removeAllScrollableFooters() {
if (mScrollableFooters.size() > 0) {
log.d("Remove all scrollable footers");
mItems.removeAll(mScrollableFooters);
notifyItemRangeRemoved(getItemCount() - mScrollableFooters.size(), mScrollableFooters.size());
mScrollableFooters.clear();
}
}
/**
* Same as {@link #addScrollableHeader(IFlexible)} but with a delay and the possibility to
* scroll to it.
*
* @param headerItem the header item to be added
* @param delay the delay in ms
* @param scrollToPosition true to scroll to the header item position once it has been added
* @see #addScrollableHeader(IFlexible)
* @since 5.0.0-rc1
*/
public final void addScrollableHeaderWithDelay(@NonNull final T headerItem, @IntRange(from = 0) long delay,
final boolean scrollToPosition) {
log.d("Enqueued adding scrollable header (%sms) %s", delay, getClassName(headerItem));
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (addScrollableHeader(headerItem) && scrollToPosition)
performScroll(getGlobalPositionOf(headerItem));
}
}, delay);
}