-
Notifications
You must be signed in to change notification settings - Fork 359
/
CardSliderLayoutManager.java
720 lines (589 loc) · 23.6 KB
/
CardSliderLayoutManager.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
package com.ramotion.cardslider;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.PointF;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.View;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
/**
* A {@link androidx.recyclerview.widget.RecyclerView.LayoutManager} implementation.
*/
public class CardSliderLayoutManager extends RecyclerView.LayoutManager
implements RecyclerView.SmoothScroller.ScrollVectorProvider {
private static final int DEFAULT_ACTIVE_CARD_LEFT_OFFSET = 50;
private static final int DEFAULT_CARD_WIDTH = 148;
private static final int DEFAULT_CARDS_GAP = 12;
private static final int LEFT_CARD_COUNT = 2;
private final SparseArray<View> viewCache = new SparseArray<>();
private final SparseIntArray cardsXCoords = new SparseIntArray();
private int cardWidth;
private int activeCardLeft;
private int activeCardRight;
private int activeCardCenter;
private float cardsGap;
private int scrollRequestedPosition = 0;
private ViewUpdater viewUpdater;
private RecyclerView recyclerView;
/**
* A ViewUpdater is invoked whenever a visible/attached card is scrolled.
*/
public interface ViewUpdater {
/**
* Called when CardSliderLayoutManager initialized
*/
void onLayoutManagerInitialized(@NonNull CardSliderLayoutManager lm);
/**
* Called on view update (scroll, layout).
* @param view Updating view
* @param position Position of card relative to the current active card position of the layout manager.
* 0 is active card. 1 is first right card, and -1 is first left (stacked) card.
*/
void updateView(@NonNull View view, float position);
}
private static class SavedState implements Parcelable {
int anchorPos;
SavedState() {
}
SavedState(Parcel in) {
anchorPos = in.readInt();
}
public SavedState(SavedState other) {
anchorPos = other.anchorPos;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(anchorPos);
}
public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel parcel) {
return new SavedState(parcel);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
/**
* Creates CardSliderLayoutManager with default values
*
* @param context Current context, will be used to access resources.
*/
public CardSliderLayoutManager(@NonNull Context context) {
this(context, null, 0, 0);
}
/**
* Constructor used when layout manager is set in XML by RecyclerView attribute
* "layoutManager".
*
* See {@link R.styleable#CardSlider_activeCardLeftOffset}
* See {@link R.styleable#CardSlider_cardWidth}
* See {@link R.styleable#CardSlider_cardsGap}
*/
public CardSliderLayoutManager(@NonNull Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
final float density = context.getResources().getDisplayMetrics().density;
final int defaultCardWidth = (int) (DEFAULT_CARD_WIDTH * density);
final int defaultActiveCardLeft = (int) (DEFAULT_ACTIVE_CARD_LEFT_OFFSET * density);
final float defaultCardsGap = DEFAULT_CARDS_GAP * density;
if (attrs == null) {
initialize(defaultActiveCardLeft, defaultCardWidth, defaultCardsGap, null);
} else {
int attrCardWidth;
int attrActiveCardLeft;
float attrCardsGap;
String viewUpdateClassName;
final TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CardSlider, 0, 0);
try {
attrCardWidth = a.getDimensionPixelSize(R.styleable.CardSlider_cardWidth, defaultCardWidth);
attrActiveCardLeft = a.getDimensionPixelSize(R.styleable.CardSlider_activeCardLeftOffset, defaultActiveCardLeft);
attrCardsGap = a.getDimension(R.styleable.CardSlider_cardsGap, defaultCardsGap);
viewUpdateClassName = a.getString(R.styleable.CardSlider_viewUpdater);
} finally {
a.recycle();
}
final ViewUpdater viewUpdater = loadViewUpdater(context, viewUpdateClassName, attrs);
initialize(attrActiveCardLeft, attrCardWidth, attrCardsGap, viewUpdater);
}
}
/**
* Creates CardSliderLayoutManager with specified values in pixels.
*
* @param activeCardLeft Active card offset from start of RecyclerView. Default value is 50dp.
* @param cardWidth Card width. Default value is 148dp.
* @param cardsGap Distance between cards. Default value is 12dp.
*/
public CardSliderLayoutManager(int activeCardLeft, int cardWidth, float cardsGap) {
initialize(activeCardLeft, cardWidth, cardsGap, null);
}
private void initialize(int left, int width, float gap, @Nullable ViewUpdater updater) {
this.cardWidth = width;
this.activeCardLeft = left;
this.activeCardRight = activeCardLeft + cardWidth;
this.activeCardCenter = activeCardLeft + ((this.activeCardRight - activeCardLeft) / 2);
this.cardsGap = gap;
this.viewUpdater = updater;
if (this.viewUpdater == null) {
this.viewUpdater = new DefaultViewUpdater();
}
viewUpdater.onLayoutManagerInitialized(this);
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return new RecyclerView.LayoutParams(
RecyclerView.LayoutParams.WRAP_CONTENT,
RecyclerView.LayoutParams.WRAP_CONTENT);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, final RecyclerView.State state) {
if (getItemCount() == 0) {
removeAndRecycleAllViews(recycler);
return;
}
if (getChildCount() == 0 && state.isPreLayout()) {
return;
}
int anchorPos = getActiveCardPosition();
if (state.isPreLayout()) {
final LinkedList<Integer> removed = new LinkedList<>();
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
final View child = getChildAt(i);
final boolean isRemoved = ((RecyclerView.LayoutParams)child.getLayoutParams()).isItemRemoved();
if (isRemoved) {
removed.add(getPosition(child));
}
}
if (removed.contains(anchorPos)) {
final int first = removed.getFirst();
final int last = removed.getLast();
final int left = first - 1;
final int right = last == getItemCount() + removed.size() - 1 ? RecyclerView.NO_POSITION : last;
anchorPos = Math.max(left, right);
}
scrollRequestedPosition = anchorPos;
}
detachAndScrapAttachedViews(recycler);
fill(anchorPos, recycler, state);
if (cardsXCoords.size() != 0) {
layoutByCoords();
}
if (state.isPreLayout()) {
recyclerView.postOnAnimationDelayed(new Runnable() {
@Override
public void run() {
updateViewScale();
}
}, 415);
} else {
updateViewScale();
}
}
@Override
public boolean supportsPredictiveItemAnimations() {
return true;
}
@Override
public void onAdapterChanged(RecyclerView.Adapter oldAdapter, RecyclerView.Adapter newAdapter) {
removeAllViews();
}
@Override
public boolean canScrollHorizontally() {
return getChildCount() != 0;
}
@Override
public void scrollToPosition(int position) {
if (position < 0 || position >= getItemCount()) {
return;
}
scrollRequestedPosition = position;
requestLayout();
}
@Override
public int scrollHorizontallyBy(int dx, RecyclerView.Recycler recycler, RecyclerView.State state) {
scrollRequestedPosition = RecyclerView.NO_POSITION;
int delta;
if (dx < 0) {
delta = scrollRight(Math.max(dx, -cardWidth));
} else {
delta = scrollLeft(dx);
}
fill(getActiveCardPosition(), recycler, state);
updateViewScale();
cardsXCoords.clear();
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
final View view = getChildAt(i);
cardsXCoords.put(getPosition(view), getDecoratedLeft(view));
}
return delta;
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return new PointF(targetPosition - getActiveCardPosition(), 0);
}
@Override
public void smoothScrollToPosition(final RecyclerView recyclerView, RecyclerView.State state, final int position) {
if (position < 0 || position >= getItemCount()) {
return;
}
final LinearSmoothScroller scroller = getSmoothScroller(recyclerView);
scroller.setTargetPosition(position);
startSmoothScroll(scroller);
}
@Override
public void onItemsRemoved(RecyclerView recyclerView, int positionStart, int count) {
final int anchorPos = getActiveCardPosition();
if (positionStart + count <= anchorPos) {
scrollRequestedPosition = anchorPos - 1;
}
}
@Override
public Parcelable onSaveInstanceState() {
SavedState state = new SavedState();
state.anchorPos = getActiveCardPosition();
return state;
}
@Override
public void onRestoreInstanceState(Parcelable parcelable) {
if (parcelable instanceof SavedState) {
SavedState state = (SavedState) parcelable;
scrollRequestedPosition = state.anchorPos;
requestLayout();
}
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
recyclerView = view;
}
@Override
public void onDetachedFromWindow(RecyclerView view, RecyclerView.Recycler recycler) {
super.onDetachedFromWindow(view, recycler);
recyclerView = null;
}
/**
* @return active card position or RecyclerView.NO_POSITION
*/
public int getActiveCardPosition() {
if (scrollRequestedPosition != RecyclerView.NO_POSITION) {
return scrollRequestedPosition;
} else {
int result = RecyclerView.NO_POSITION;
View biggestView = null;
float lastScaleX = 0f;
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
final View child = getChildAt(i);
final int viewLeft = getDecoratedLeft(child);
if (viewLeft >= activeCardRight) {
continue;
}
final float scaleX = ViewCompat.getScaleX(child);
if (lastScaleX < scaleX && viewLeft < activeCardCenter) {
lastScaleX = scaleX;
biggestView = child;
}
}
if (biggestView != null) {
result = getPosition(biggestView);
}
return result;
}
}
@Nullable
public View getTopView() {
if (getChildCount() == 0) {
return null;
}
View result = null;
float lastValue = cardWidth;
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
final View child = getChildAt(i);
if (getDecoratedLeft(child) >= activeCardRight) {
continue;
}
final int viewLeft = getDecoratedLeft(child);
final int diff = activeCardRight - viewLeft;
if (diff < lastValue) {
lastValue = diff;
result = child;
}
}
return result;
}
public int getActiveCardLeft() {
return activeCardLeft;
}
public int getActiveCardRight() {
return activeCardRight;
}
public int getActiveCardCenter() {
return activeCardCenter;
}
public int getCardWidth() {
return cardWidth;
}
public float getCardsGap() {
return cardsGap;
}
public LinearSmoothScroller getSmoothScroller(final RecyclerView recyclerView) {
return new LinearSmoothScroller(recyclerView.getContext()) {
@Override
public int calculateDxToMakeVisible(View view, int snapPreference) {
final int viewStart = getDecoratedLeft(view);
if (viewStart > activeCardLeft) {
return activeCardLeft - viewStart;
} else {
int delta = 0;
int topViewPos = 0;
final View topView = getTopView();
if (topView != null) {
topViewPos = getPosition(topView);
if (topViewPos != getTargetPosition()) {
final int topViewLeft = getDecoratedLeft(topView);
if (topViewLeft >= activeCardLeft && topViewLeft < activeCardRight) {
delta = activeCardRight - topViewLeft;
}
}
}
return delta + (cardWidth) * Math.max(0, topViewPos - getTargetPosition() - 1);
}
}
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 0.5f;
}
};
}
private ViewUpdater loadViewUpdater(Context context, String className, AttributeSet attrs) {
if (className == null || className.trim().length() == 0) {
return null;
}
final String fullClassName;
if (className.charAt(0) == '.') {
fullClassName = context.getPackageName() + className;
} else if (className.contains(".")) {
fullClassName = className;
} else {
fullClassName = CardSliderLayoutManager.class.getPackage().getName() + '.' + className;
}
ViewUpdater updater;
try {
final ClassLoader classLoader = context.getClassLoader();
final Class<? extends ViewUpdater> viewUpdaterClass =
classLoader.loadClass(fullClassName).asSubclass(ViewUpdater.class);
final Constructor<? extends ViewUpdater> constructor =
viewUpdaterClass.getConstructor();
constructor.setAccessible(true);
updater = constructor.newInstance();
} catch (NoSuchMethodException e) {
throw new IllegalStateException(attrs.getPositionDescription() +
": Error creating LayoutManager " + className, e);
} catch (ClassNotFoundException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Unable to find ViewUpdater" + className, e);
} catch (InvocationTargetException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Could not instantiate the ViewUpdater: " + className, e);
} catch (InstantiationException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Could not instantiate the ViewUpdater: " + className, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Cannot access non-public constructor " + className, e);
} catch (ClassCastException e) {
throw new IllegalStateException(attrs.getPositionDescription()
+ ": Class is not a ViewUpdater " + className, e);
}
return updater;
}
private int scrollRight(int dx) {
final int childCount = getChildCount();
if (childCount == 0) {
return 0;
}
final View rightestView = getChildAt(childCount - 1);
final int deltaBorder = activeCardLeft + getPosition(rightestView) * cardWidth;
final int delta = getAllowedRightDelta(rightestView, dx, deltaBorder);
final LinkedList<View> rightViews = new LinkedList<>();
final LinkedList<View> leftViews = new LinkedList<>();
for (int i = childCount - 1; i >= 0; i--) {
final View view = getChildAt(i);
final int viewLeft = getDecoratedLeft(view);
if (viewLeft >= activeCardRight) {
rightViews.add(view);
} else {
leftViews.add(view);
}
}
for (View view: rightViews) {
final int border = activeCardLeft + getPosition(view) * cardWidth;
final int allowedDelta = getAllowedRightDelta(view, dx, border);
view.offsetLeftAndRight(-allowedDelta);
}
final int step = activeCardLeft / LEFT_CARD_COUNT;
final int jDelta = (int) Math.floor(1f * delta * step / cardWidth);
View prevView = null;
int j = 0;
for (int i = 0, cnt = leftViews.size(); i < cnt; i++) {
final View view = leftViews.get(i);
if (prevView == null || getDecoratedLeft(prevView) >= activeCardRight) {
final int border = activeCardLeft + getPosition(view) * cardWidth;
final int allowedDelta = getAllowedRightDelta(view, dx, border);
view.offsetLeftAndRight(-allowedDelta);
} else {
final int border = activeCardLeft - step * j;
view.offsetLeftAndRight(-getAllowedRightDelta(view, jDelta, border));
j++;
}
prevView = view;
}
return delta;
}
private int scrollLeft(int dx) {
final int childCount = getChildCount();
if (childCount == 0) {
return 0;
}
final View lastView = getChildAt(childCount - 1);
final boolean isLastItem = getPosition(lastView) == getItemCount() - 1;
final int delta;
if (isLastItem) {
delta = Math.min(dx, getDecoratedRight(lastView) - activeCardRight);
} else {
delta = dx;
}
final int step = activeCardLeft / LEFT_CARD_COUNT;
final int jDelta = (int) Math.ceil(1f * delta * step / cardWidth);
for (int i = childCount - 1; i >= 0; i--) {
final View view = getChildAt(i);
final int viewLeft = getDecoratedLeft(view);
if (viewLeft > activeCardLeft) {
view.offsetLeftAndRight(getAllowedLeftDelta(view, delta, activeCardLeft));
} else {
int border = activeCardLeft - step;
for (int j = i; j >= 0; j--) {
final View jView = getChildAt(j);
jView.offsetLeftAndRight(getAllowedLeftDelta(jView, jDelta, border));
border -= step;
}
break;
}
}
return delta;
}
private int getAllowedLeftDelta(@NonNull View view, int dx, int border) {
final int viewLeft = getDecoratedLeft(view);
if (viewLeft - dx > border) {
return -dx;
} else {
return border - viewLeft;
}
}
private int getAllowedRightDelta(@NonNull View view, int dx, int border) {
final int viewLeft = getDecoratedLeft(view);
if (viewLeft + Math.abs(dx) < border) {
return dx;
} else {
return viewLeft - border;
}
}
private void layoutByCoords() {
final int count = Math.min(getChildCount(), cardsXCoords.size());
for (int i = 0; i < count; i++) {
final View view = getChildAt(i);
final int viewLeft = cardsXCoords.get(getPosition(view));
layoutDecorated(view, viewLeft, 0, viewLeft + cardWidth, getDecoratedBottom(view));
}
cardsXCoords.clear();
}
private void fill(int anchorPos, RecyclerView.Recycler recycler, RecyclerView.State state) {
viewCache.clear();
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
View view = getChildAt(i);
int pos = getPosition(view);
viewCache.put(pos, view);
}
for (int i = 0, cnt = viewCache.size(); i < cnt; i++) {
detachView(viewCache.valueAt(i));
}
if (!state.isPreLayout()) {
fillLeft(anchorPos, recycler);
fillRight(anchorPos, recycler);
}
for (int i = 0, cnt = viewCache.size(); i < cnt; i++) {
recycler.recycleView(viewCache.valueAt(i));
}
}
private void fillLeft(int anchorPos, RecyclerView.Recycler recycler) {
if (anchorPos == RecyclerView.NO_POSITION) {
return;
}
final int layoutStep = activeCardLeft / LEFT_CARD_COUNT;
int pos = Math.max(0, anchorPos - LEFT_CARD_COUNT - 1);
int viewLeft = Math.max(-1, LEFT_CARD_COUNT - (anchorPos - pos)) * layoutStep;
while (pos < anchorPos) {
View view = viewCache.get(pos);
if (view != null) {
attachView(view);
viewCache.remove(pos);
} else {
view = recycler.getViewForPosition(pos);
addView(view);
measureChildWithMargins(view, 0, 0);
final int viewHeight = getDecoratedMeasuredHeight(view);
layoutDecorated(view, viewLeft, 0, viewLeft + cardWidth, viewHeight);
}
viewLeft += layoutStep;
pos++;
}
}
private void fillRight(int anchorPos, RecyclerView.Recycler recycler) {
if (anchorPos == RecyclerView.NO_POSITION) {
return;
}
final int width = getWidth();
final int itemCount = getItemCount();
int pos = anchorPos;
int viewLeft = activeCardLeft;
boolean fillRight = true;
while (fillRight && pos < itemCount) {
View view = viewCache.get(pos);
if (view != null) {
attachView(view);
viewCache.remove(pos);
} else {
view = recycler.getViewForPosition(pos);
addView(view);
measureChildWithMargins(view, 0, 0);
final int viewHeight = getDecoratedMeasuredHeight(view);
layoutDecorated(view, viewLeft, 0, viewLeft + cardWidth, viewHeight);
}
viewLeft = getDecoratedRight(view);
fillRight = viewLeft < width + cardWidth;
pos++;
}
}
private void updateViewScale() {
for (int i = 0, cnt = getChildCount(); i < cnt; i++) {
final View view = getChildAt(i);
final int viewLeft = getDecoratedLeft(view);
final float position = ((float) (viewLeft - activeCardLeft) / cardWidth);
viewUpdater.updateView(view, position);
}
}
}