-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathCarouselLayoutManager.java
1749 lines (1559 loc) · 67.9 KB
/
CarouselLayoutManager.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 2022 The Android Open Source Project
*
* 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
*
* https://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.google.android.material.carousel;
import com.google.android.material.R;
import static androidx.recyclerview.widget.RecyclerView.NO_POSITION;
import static com.google.android.material.animation.AnimationUtils.lerp;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.lang.Math.min;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.LayoutManager;
import androidx.recyclerview.widget.RecyclerView.LayoutParams;
import androidx.recyclerview.widget.RecyclerView.Recycler;
import androidx.recyclerview.widget.RecyclerView.State;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.View.OnLayoutChangeListener;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import androidx.annotation.IntDef;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RestrictTo;
import androidx.annotation.RestrictTo.Scope;
import androidx.annotation.VisibleForTesting;
import androidx.core.graphics.ColorUtils;
import androidx.core.math.MathUtils;
import androidx.core.util.Preconditions;
import com.google.android.material.carousel.CarouselStrategy.StrategyType;
import com.google.android.material.carousel.KeylineState.Keyline;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* A {@link LayoutManager} that can mask and offset items along the scrolling axis, creating a
* unique list optimized for a stylized viewing experience.
*
* <p>{@link CarouselLayoutManager} requires all children to use {@link MaskableFrameLayout} as
* their root ViewGroup.
*
* <p>Note that when Carousel measures and lays out items, the first item in the adapter will be
* measured and it's desired size will be used to determine an appropriate size for all items in the
* carousel.
*
* <p>For more information, see the <a
* href="https://github.com/material-components/material-components-android/blob/master/docs/components/Carousel.md">component
* developer guidance</a> and <a href="https://material.io/components/carousel/overview">design
* guidelines</a>.
*/
public class CarouselLayoutManager extends LayoutManager
implements Carousel, RecyclerView.SmoothScroller.ScrollVectorProvider {
private static final String TAG = "CarouselLayoutManager";
@VisibleForTesting int scrollOffset;
// Min scroll is the offset number that offsets the list to the right/bottom as much as possible.
// In LTR layouts, this will be the scroll offset to move to the start of the container. In RTL,
// this will move the list to the end of the container.
@VisibleForTesting int minScroll;
// Max scroll is the offset number that moves the list to the left/top of the list as much as
// possible. In LTR layouts, this will move the list to the end of the container. In RTL, this
// will move the list to the start of the container.
@VisibleForTesting int maxScroll;
private boolean isDebuggingEnabled = false;
private final DebugItemDecoration debugItemDecoration = new DebugItemDecoration();
@NonNull private CarouselStrategy carouselStrategy;
@Nullable private KeylineStateList keylineStateList;
// A KeylineState shifted for any current scroll offset.
@Nullable private KeylineState currentKeylineState;
// Tracks the last position to be at child index 0 after the most recent call to #fill. This helps
// optimize fill loops by starting the fill from an adapter position that will need the least
// number of loop iterations to fill the RecyclerView.
private int currentFillStartPosition = 0;
// Tracks the keyline state associated with each item in the RecyclerView.
@Nullable private Map<Integer, KeylineState> keylineStatePositionMap;
/** Horizontal orientation for Carousel. */
public static final int HORIZONTAL = RecyclerView.HORIZONTAL;
/** Vertical orientation for Carousel. */
public static final int VERTICAL = RecyclerView.VERTICAL;
private CarouselOrientationHelper orientationHelper;
private final OnLayoutChangeListener recyclerViewSizeChangeListener =
(v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
// If RV width or height values have changed, refresh the keyline state.
if ((right - left != oldRight - oldLeft) || (bottom - top != oldBottom - oldTop)) {
v.post(this::refreshKeylineState);
}
};
/** Aligns large items to the start of the carousel. */
public static final int ALIGNMENT_START = 0;
/** Aligns large items to the center of the carousel. */
public static final int ALIGNMENT_CENTER = 1;
private int lastItemCount;
/**
* An estimation of the current focused position, determined by which item center is closest to
* the first focal keyline. This is used when restoring item position after the carousel keylines
* are re-calculated due to configuration or size changes.
*/
private int currentEstimatedPosition = NO_POSITION;
/**
* Determines where to align the large items in the carousel.
*
* @hide
*/
@IntDef({ALIGNMENT_START, ALIGNMENT_CENTER})
@Retention(RetentionPolicy.SOURCE)
@interface Alignment {}
@Alignment private int carouselAlignment = ALIGNMENT_START;
/**
* An internal object used to store and run checks on a child to be potentially added to the
* RecyclerView and laid out.
*/
private static final class ChildCalculations {
final View child;
final float center;
final float offsetCenter;
final KeylineRange range;
/**
* Creates new calculations object.
*
* @param child The child being calculated for
* @param center the location of the center of the {@code child} along the scrolling axis in the
* end-to-end model
* @param offsetCenter the offset location of the center of the {@code child} along the
* scrolling axis where this child will be laid out
* @param range the keyline range that surrounds {@code locOffset}
*/
ChildCalculations(View child, float center, float offsetCenter, KeylineRange range) {
this.child = child;
this.center = center;
this.offsetCenter = offsetCenter;
this.range = range;
}
}
public CarouselLayoutManager() {
this(new MultiBrowseCarouselStrategy());
}
public CarouselLayoutManager(@NonNull CarouselStrategy strategy) {
this(strategy, HORIZONTAL);
}
public CarouselLayoutManager(
@NonNull CarouselStrategy strategy, @RecyclerView.Orientation int orientation) {
setCarouselStrategy(strategy);
setOrientation(orientation);
}
@SuppressLint("UnknownNullness") // b/240775049: Cannot annotate properly
public CarouselLayoutManager(
Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
setCarouselStrategy(new MultiBrowseCarouselStrategy());
setCarouselAttributes(context, attrs);
}
private void setCarouselAttributes(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Carousel);
setCarouselAlignment(a.getInt(R.styleable.Carousel_carousel_alignment, ALIGNMENT_START));
setOrientation(
a.getInt(
androidx.recyclerview.R.styleable.RecyclerView_android_orientation,
HORIZONTAL));
a.recycle();
}
}
/**
* Recalculates the internal state of the Carousel based on the size of the items. This should be
* called whenever the size of the items is changed.
*/
public void notifyItemSizeChanged() {
refreshKeylineState();
}
/**
* Sets the alignment of the focal items in the carousel.
*/
public void setCarouselAlignment(@Alignment int alignment) {
this.carouselAlignment = alignment;
refreshKeylineState();
}
@Override
public int getCarouselAlignment() {
return carouselAlignment;
}
private int getLeftOrTopPaddingForKeylineShift() {
// TODO(b/316969331): Fix keyline shifting by decreasing carousel size when carousel is clipped
// to padding.
if (getClipToPadding()) {
return 0;
}
if (getOrientation() == VERTICAL) {
return getPaddingTop();
}
return getPaddingLeft();
}
private int getRightOrBottomPaddingForKeylineShift() {
// TODO(b/316969331): Fix keyline shifting by decreasing carousel size when carousel is clipped
// to padding.
if (getClipToPadding()) {
return 0;
}
if (getOrientation() == VERTICAL) {
return getPaddingBottom();
}
return getPaddingRight();
}
@Override
public LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
/**
* Sets the {@link CarouselStrategy} used by this layout manager to mask and offset child views as
* they move along the scrolling axis.
*/
public void setCarouselStrategy(@NonNull CarouselStrategy carouselStrategy) {
this.carouselStrategy = carouselStrategy;
refreshKeylineState();
}
@Override
public void onAttachedToWindow(RecyclerView view) {
super.onAttachedToWindow(view);
carouselStrategy.initialize(view.getContext());
refreshKeylineState();
view.addOnLayoutChangeListener(recyclerViewSizeChangeListener);
}
@Override
public void onDetachedFromWindow(RecyclerView view, Recycler recycler) {
super.onDetachedFromWindow(view, recycler);
view.removeOnLayoutChangeListener(recyclerViewSizeChangeListener);
}
@Override
public void onLayoutChildren(Recycler recycler, State state) {
if (state.getItemCount() <= 0 || getContainerSize() <= 0f) {
removeAndRecycleAllViews(recycler);
currentFillStartPosition = 0;
return;
}
boolean isRtl = isLayoutRtl();
boolean isInitialLoad = keylineStateList == null;
// If a keyline state hasn't been created or is the wrong size, use the first child as a
// representative of how each child would like to be measured and allow the strategy to create
// a keyline state.
if (isInitialLoad
|| keylineStateList.getDefaultState().getCarouselSize() != getContainerSize()) {
recalculateKeylineStateList(recycler);
}
// Ensure our scroll limits are initialized and valid for the data set size.
int startScroll = calculateStartScroll(keylineStateList);
int endScroll = calculateEndScroll(state, keylineStateList);
// Convert the layout-direction-aware offsets into min/max absolutes. These need to be in the
// min/max format so they can be correctly passed to KeylineStateList and used to interpolate
// between keyline states.
minScroll = isRtl ? endScroll : startScroll;
maxScroll = isRtl ? startScroll : endScroll;
if (isInitialLoad) {
// Scroll to the start of the list on first load.
scrollOffset = startScroll;
keylineStatePositionMap =
keylineStateList.getKeylineStateForPositionMap(
getItemCount(), minScroll, maxScroll, isLayoutRtl());
if (currentEstimatedPosition != NO_POSITION) {
scrollOffset =
getScrollOffsetForPosition(
currentEstimatedPosition, getKeylineStateForPosition(currentEstimatedPosition));
}
}
// Clamp the scroll offset by the new min and max by pinging the scroll by calculator
// with a 0 delta.
scrollOffset += calculateShouldScrollBy(0, scrollOffset, minScroll, maxScroll);
// Ensure currentFillStartPosition is valid if the number of items in the adapter has changed.
currentFillStartPosition = MathUtils.clamp(currentFillStartPosition, 0, state.getItemCount());
updateCurrentKeylineStateForScrollOffset(keylineStateList);
detachAndScrapAttachedViews(recycler);
fill(recycler, state);
lastItemCount = getItemCount();
}
@Override
public boolean isAutoMeasureEnabled() {
return true;
}
private void recalculateKeylineStateList(Recycler recycler) {
View firstChild = recycler.getViewForPosition(0);
measureChildWithMargins(firstChild, 0, 0);
KeylineState keylineState = carouselStrategy.onFirstChildMeasuredWithMargins(this, firstChild);
keylineStateList =
KeylineStateList.from(
this,
isLayoutRtl() ? KeylineState.reverse(keylineState, getContainerSize()) : keylineState,
getItemMargins(),
getLeftOrTopPaddingForKeylineShift(),
getRightOrBottomPaddingForKeylineShift(),
carouselStrategy.getStrategyType());
}
private int getItemMargins() {
if (getChildCount() > 0) {
LayoutParams lp = (LayoutParams) getChildAt(0).getLayoutParams();
if (orientationHelper.orientation == HORIZONTAL) {
return lp.leftMargin + lp.rightMargin;
}
return lp.topMargin + lp.bottomMargin;
}
return 0;
}
/**
* Recalculates the {@link KeylineState} and {@link KeylineStateList} for the current strategy.
*/
private void refreshKeylineState() {
keylineStateList = null;
requestLayout();
}
/**
* Adds and places children into the {@link RecyclerView}, handling child layout and recycling
* according to this class' {@link CarouselStrategy}.
*
* <p>This method is responsible for making sure views are added when additional space is created
* due to an initial layout or a scroll event. All offsetting due to scroll events is done by
* {@link #scrollBy(int, Recycler, State)}.
*
* <p>This layout manager tracks item location using two "models". The first is an end-to-end
* model that keeps track of items as if they were laid out one after the other and fully unmasked
* (the same way they would be laid out in a traditional list). This model is primarily useful for
* tracking scroll minimums, maximums, and offsets. The second model is an offset model which is
* the location of an item after it's position has been interpolated from {@link Keyline#loc}
* (it's end-to-end location) to {@link Keyline#locOffset}. This is the model in which children
* are actually laid out and drawn.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
* @param state state passed by the {@link RecyclerView} with useful information like item count
* and focal state
*/
private void fill(Recycler recycler, State state) {
removeAndRecycleOutOfBoundsViews(recycler);
if (getChildCount() == 0) {
// First layout or the data set has changed. Re-layout all views by filling from start to end.
addViewsStart(recycler, currentFillStartPosition - 1);
addViewsEnd(recycler, state, currentFillStartPosition);
} else {
// Fill the container where there is now empty space after scrolling.
int firstPosition = getPosition(getChildAt(0));
int lastPosition = getPosition(getChildAt(getChildCount() - 1));
addViewsStart(recycler, firstPosition - 1);
addViewsEnd(recycler, state, lastPosition + 1);
}
validateChildOrderIfDebugging();
}
@Override
public void onLayoutCompleted(State state) {
super.onLayoutCompleted(state);
if (getChildCount() == 0) {
currentFillStartPosition = 0;
} else {
currentFillStartPosition = getPosition(getChildAt(0));
}
validateChildOrderIfDebugging();
}
/**
* Adds views to the RecyclerView, moving towards the start of the carousel container, until
* potentially new items are no longer in bounds or the beginning of the adapter list is reached.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
* @param startPosition the adapter position from which to start adding views
*/
private void addViewsStart(Recycler recycler, int startPosition) {
float start = calculateChildStartForFill(startPosition);
for (int i = startPosition; i >= 0; i--) {
float center = addEnd(start, currentKeylineState.getItemSize() / 2F);
KeylineRange range =
getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, false);
float offsetCenter = calculateChildOffsetCenterForLocation(center, range);
if (isLocOffsetOutOfFillBoundsStart(offsetCenter, range)) {
break;
}
start = addStart(start, currentKeylineState.getItemSize());
// If this child's start is beyond the end of the container, don't add the child but continue
// to loop so we can eventually get to children that are within bounds.
if (isLocOffsetOutOfFillBoundsEnd(offsetCenter, range)) {
continue;
}
View child = recycler.getViewForPosition(i);
// Add this child to the first index of the RecyclerView.
addAndLayoutView(
child, /* index= */ 0, new ChildCalculations(child, center, offsetCenter, range));
}
}
/**
* Adds a child view to the RecyclerView at the given {@code childIndex}, regardless of whether or
* not the view is in bounds.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
* @param startPosition the position of the adapter whose view is to be added
* @param childIndex the index of the RecyclerView's children that the view should be added at
*/
private void addViewAtPosition(@NonNull Recycler recycler, int startPosition, int childIndex) {
if (startPosition < 0 || startPosition >= getItemCount()) {
return;
}
float start = calculateChildStartForFill(startPosition);
ChildCalculations calculations = makeChildCalculations(recycler, start, startPosition);
// Add this child to the given child index of the RecyclerView.
addAndLayoutView(calculations.child, /* index= */ childIndex, calculations);
}
/**
* Adds views to the RecyclerView, moving towards the end of the carousel container, until
* potentially new items are no longer in bounds or the end of the adapter list is reached.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
* @param state state passed by the {@link RecyclerView} used here to determine item count
* @param startPosition the adapter position from which to start adding views
*/
private void addViewsEnd(Recycler recycler, State state, int startPosition) {
float start = calculateChildStartForFill(startPosition);
for (int i = startPosition; i < state.getItemCount(); i++) {
float center = addEnd(start, currentKeylineState.getItemSize() / 2F);
KeylineRange range =
getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, false);
float offsetCenter = calculateChildOffsetCenterForLocation(center, range);
if (isLocOffsetOutOfFillBoundsEnd(offsetCenter, range)) {
break;
}
start = addEnd(start, currentKeylineState.getItemSize());
// If this child's end is beyond the start of the container, don't add the child but continue
// to loop so we can eventually get to children that are within bounds.
if (isLocOffsetOutOfFillBoundsStart(offsetCenter, range)) {
continue;
}
View child = recycler.getViewForPosition(i);
// Add this child to the last index of the RecyclerView
addAndLayoutView(
child, /* index= */ -1, new ChildCalculations(child, center, offsetCenter, range));
}
}
/** Used for debugging. Logs the internal representation of children to default logger. */
private void logChildrenIfDebugging() {
if (!isDebuggingEnabled) {
return;
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "internal representation of views on the screen");
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
float center = getDecoratedCenterWithMargins(child);
Log.d(
TAG,
"item position " + getPosition(child) + ", center:" + center + ", child index:" + i);
}
Log.d(TAG, "==============");
}
}
/**
* Used for debugging. Validates that child views are laid out in correct order. This is important
* because rest of the algorithm relies on this constraint.
*
* <p>Child 0 should be closest to adapter position 0 and last child should be closest to the last
* adapter position.
*/
private void validateChildOrderIfDebugging() {
if (!isDebuggingEnabled || getChildCount() < 1) {
return;
}
for (int i = 0; i < getChildCount() - 1; i++) {
int currPos = getPosition(getChildAt(i));
int nextPos = getPosition(getChildAt(i + 1));
if (currPos > nextPos) {
logChildrenIfDebugging();
throw new IllegalStateException(
"Detected invalid child order. Child at index ["
+ i
+ "] had adapter position ["
+ currPos
+ "] and child at index ["
+ (i + 1)
+ "] had adapter position ["
+ nextPos
+ "].");
}
}
}
/**
* Calculates position and mask for a view at at adapter {@code position} and returns an object
* with the calculated values.
*
* <p>The returned object is used to run any checks/validations around whether or not this child
* should be added to the RecyclerView given its calculated location.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
* @param start the start location of this items view in the end-to-end layout model
* @param position the adapter position of the item to add
* @return a {@link ChildCalculations} object
*/
private ChildCalculations makeChildCalculations(Recycler recycler, float start, int position) {
View child = recycler.getViewForPosition(position);
measureChildWithMargins(child, 0, 0);
float center = addEnd(start, currentKeylineState.getItemSize() / 2F);
KeylineRange range =
getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, false);
float offsetCenter = calculateChildOffsetCenterForLocation(center, range);
return new ChildCalculations(child, center, offsetCenter, range);
}
/**
* Adds a child to the RecyclerView and lays it out with its center at {@code offsetCx} on the
* scrolling axis.
*
* @param child the child view to add and lay out
* @param index the index at which to add the child to the RecyclerView. Use 0 for adding to the
* start of the list and -1 for adding to the end.
* @param calculations the child calculations to be used to layout this view
*/
private void addAndLayoutView(View child, int index, ChildCalculations calculations) {
float halfItemSize = currentKeylineState.getItemSize() / 2F;
addView(child, index);
measureChildWithMargins(child, 0, 0);
int start = (int) (calculations.offsetCenter - halfItemSize);
int end = (int) (calculations.offsetCenter + halfItemSize);
orientationHelper.layoutDecoratedWithMargins(child, start, end);
updateChildMaskForLocation(child, calculations.center, calculations.range);
}
/**
* Returns true if a view rendered at {@code locOffset} will be completely out of bounds (its end
* comes before the start of the container) when masked according to the {@code KeylineRange}.
*
* <p>Use this method to determine whether or not a child whose center is at {@code locOffset}
* should be added to the RecyclerView.
*
* @param locOffset the center of the view to be checked along the scroll axis
* @param range the keyline range surrounding {@code locOffset}
* @return true if the end of a masked view, whose center is at {@code locOffset}, will come
* before the start of the container.
*/
private boolean isLocOffsetOutOfFillBoundsStart(float locOffset, KeylineRange range) {
float maskedSize = getMaskedItemSizeForLocOffset(locOffset, range);
float maskedEnd = addEnd(locOffset, maskedSize / 2F);
return isLayoutRtl() ? maskedEnd > getContainerSize() : maskedEnd < 0;
}
@Override
public boolean isHorizontal() {
return orientationHelper.orientation == HORIZONTAL;
}
/**
* Returns true if a view rendered at {@code locOffset} will be completely out of bounds (its
* start comes after the end of the container) when masked according to the {@code KeylineRange}.
*
* <p>Use this method to determine whether or not a child whose center is at {@code locOffset}
* should be added to the RecyclerView.
*
* @param locOffset the center of the view to be checked along the scroll axis
* @param range the keyline range surrounding {@code locOffset}
* @return true if the start of a masked view, whose center is at {@code locOffset}, will come
* after the start of the container.
*/
private boolean isLocOffsetOutOfFillBoundsEnd(float locOffset, KeylineRange range) {
float maskedSize = getMaskedItemSizeForLocOffset(locOffset, range);
float maskedStart = addStart(locOffset, maskedSize / 2F);
return isLayoutRtl() ? maskedStart < 0 : maskedStart > getContainerSize();
}
/**
* Returns the masked, decorated bounds with margins for {@code view}.
*
* <p>Note that this differs from the super method which returns the fully unmasked bounds of
* {@code view}.
*
* <p>Getting the masked, decorated bounds is useful for item decorations and other associated
* classes which need the actual visual bounds of an item in the RecyclerView. If the full,
* unmasked bounds is needed, see {@link RecyclerView#getDecoratedBoundsWithMargins(View, Rect)}.
*
* @param view the view element to check
* @param outBounds a rect that will receive the bounds of the element including its maks,
* decoration, and margins.
*/
@Override
public void getDecoratedBoundsWithMargins(@NonNull View view, @NonNull Rect outBounds) {
super.getDecoratedBoundsWithMargins(view, outBounds);
float center = outBounds.centerY();
if (isHorizontal()) {
center = outBounds.centerX();
}
float maskedSize =
getMaskedItemSizeForLocOffset(
center, getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, true));
float deltaX = isHorizontal() ? (outBounds.width() - maskedSize) / 2F : 0;
float deltaY = isHorizontal() ? 0 : (outBounds.height() - maskedSize) / 2F;
outBounds.set(
(int) (outBounds.left + deltaX),
(int) (outBounds.top + deltaY),
(int) (outBounds.right - deltaX),
(int) (outBounds.bottom - deltaY));
}
private float getDecoratedCenterWithMargins(View child) {
Rect bounds = new Rect();
super.getDecoratedBoundsWithMargins(child, bounds);
if (isHorizontal()) {
return bounds.centerX();
}
return bounds.centerY();
}
/**
* Remove and recycle any views outside of the bounds of this carousel.
*
* <p>This method uses two loops, one starting from the head of the list and one from the tail.
* This tries to check as few items as necessary before finding the first head or tail child that
* is in bounds.
*
* @param recycler current recycler that is attached to the {@link RecyclerView}
*/
private void removeAndRecycleOutOfBoundsViews(Recycler recycler) {
// Remove items that are out of bounds at the head of the list
while (getChildCount() > 0) {
View child = getChildAt(0);
float center = getDecoratedCenterWithMargins(child);
KeylineRange range =
getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, true);
if (isLocOffsetOutOfFillBoundsStart(center, range)) {
removeAndRecycleView(child, recycler);
} else {
break;
}
}
// Remove items that are out of bounds at the tail of the list
while (getChildCount() - 1 >= 0) {
View child = getChildAt(getChildCount() - 1);
float center = getDecoratedCenterWithMargins(child);
KeylineRange range =
getSurroundingKeylineRange(currentKeylineState.getKeylines(), center, true);
if (isLocOffsetOutOfFillBoundsEnd(center, range)) {
removeAndRecycleView(child, recycler);
} else {
break;
}
}
}
/**
* Finds the keylines located immediately before and after {@code location}, forming a keyline
* range that {@code location} is currently within.
*
* <p>When looking before {@code location}, the nearest keyline with the lowest index is found.
* When looking after {@code location}, the nearest keyline with the highest index is found. This
* avoids conflicts if two keylines share the same location and allows keylines to be pinned
* together.
*
* <p>If no keyline is found for the left, the left-most keyline is returned. If no keyline to the
* right is found, the right-most keyline is returned. If the orientation is vertical, the same
* goes for top-most and bottom-most keylines respectively. This means the {@code location} is
* outside the bounds of the outer-most keylines.
*
* @param location The location along the scrolling axis that should be contained by the returned
* keyline range. This can be either a location in the end-to-end model ({@link Keyline#loc}
* or in the offset model {@link Keyline#locOffset}.
* @param isOffset true if {@code location} has been offset and should be compared against {@link
* Keyline#locOffset}, false if {@code location} should be compared against {@link
* Keyline#loc}.
* @return A pair whose first item is the nearest {@link Keyline} before center and whose second
* item is the nearest {@link Keyline} after center.
*/
private static KeylineRange getSurroundingKeylineRange(
List<Keyline> keylines, float location, boolean isOffset) {
int startMinDistanceIndex = -1;
float startMinDistance = Float.MAX_VALUE;
int startMostIndex = -1;
float startMostX = Float.MAX_VALUE;
int endMinDistanceIndex = -1;
float endMinDistance = Float.MAX_VALUE;
int endMostIndex = -1;
float endMostX = -Float.MAX_VALUE;
for (int i = 0; i < keylines.size(); i++) {
Keyline keyline = keylines.get(i);
float currentLoc = isOffset ? keyline.locOffset : keyline.loc;
float delta = abs(currentLoc - location);
// Find the keyline closest to the left of center with the lowest index.
if (currentLoc <= location) {
if (delta <= startMinDistance) {
startMinDistance = delta;
startMinDistanceIndex = i;
}
}
// The keyline is to the right of center
// Find the keyline closest to the right of center with the greatest index.
if (currentLoc > location && delta <= endMinDistance) {
endMinDistance = delta;
endMinDistanceIndex = i;
}
// Find the left-most keyline
if (currentLoc <= startMostX) {
startMostIndex = i;
startMostX = currentLoc;
}
// Find the right-most keyline
if (currentLoc > endMostX) {
endMostIndex = i;
endMostX = currentLoc;
}
}
// If a keyline to the left or right hasn't been found, center is outside the bounds of the
// outer-most keylines. Use the outer-most keyline instead.
if (startMinDistanceIndex == -1) {
startMinDistanceIndex = startMostIndex;
}
if (endMinDistanceIndex == -1) {
endMinDistanceIndex = endMostIndex;
}
return new KeylineRange(
keylines.get(startMinDistanceIndex), keylines.get(endMinDistanceIndex));
}
private KeylineState getKeylineStartingState(KeylineStateList keylineStateList) {
return isLayoutRtl() ? keylineStateList.getEndState() : keylineStateList.getStartState();
}
/**
* Update the current keyline state by shifting it in response to any change in scroll offset.
*
* <p>This method should be called any time a change in the scroll offset occurs.
*/
private void updateCurrentKeylineStateForScrollOffset(
@NonNull KeylineStateList keylineStateList) {
if (maxScroll <= minScroll) {
// We don't have enough items in the list to scroll and we should use the keyline state
// that aligns items to the start of the container.
this.currentKeylineState = getKeylineStartingState(keylineStateList);
} else {
this.currentKeylineState =
keylineStateList.getShiftedState(scrollOffset, minScroll, maxScroll);
}
debugItemDecoration.setKeylines(currentKeylineState.getKeylines());
}
/**
* Calculates the distance children should be scrolled by for a given {@code delta}.
*
* @param delta the delta, resulting from a gesture or other event, that the list would like to be
* scrolled by
* @param currentScroll the current scroll offset that is always between the min and max scroll
* @param minScroll the minimum scroll offset allowed
* @param maxScroll the maximum scroll offset allowed
* @return an int that represents the change that should be applied to the current scroll offset,
* given limitations by the min and max scroll offset values
*/
private static int calculateShouldScrollBy(
int delta, int currentScroll, int minScroll, int maxScroll) {
int targetScroll = currentScroll + delta;
if (targetScroll < minScroll) {
return minScroll - currentScroll;
} else if (targetScroll > maxScroll) {
return maxScroll - currentScroll;
} else {
return delta;
}
}
/**
* Calculates the total offset needed to scroll the first item in the list to the center of the
* start focal keyline.
*/
private int calculateStartScroll(@NonNull KeylineStateList stateList) {
boolean isRtl = isLayoutRtl();
KeylineState startState = isRtl ? stateList.getEndState() : stateList.getStartState();
Keyline startFocalKeyline =
isRtl ? startState.getLastFocalKeyline() : startState.getFirstFocalKeyline();
float firstItemStart = addStart(startFocalKeyline.loc, startState.getItemSize() / 2F);
// This value already includes any padding since startFocalKeyline.loc is already adjusted
return (int) (getParentStart() - firstItemStart);
}
/**
* Calculates the total offset needed to scroll the last item in the list to the center of the end
* focal keyline.
*/
private int calculateEndScroll(State state, KeylineStateList stateList) {
boolean isRtl = isLayoutRtl();
KeylineState endState = isRtl ? stateList.getStartState() : stateList.getEndState();
Keyline endFocalKeyline =
isRtl ? endState.getFirstFocalKeyline() : endState.getLastFocalKeyline();
// Get the total distance from the first item to the last item in the end-to-end model
float lastItemDistanceFromFirstItem =
((state.getItemCount() - 1) * endState.getItemSize()) * (isRtl ? -1F : 1F);
float endFocalLocDistanceFromStart = endFocalKeyline.loc - getParentStart();
// We want the last item in the list to only be able to scroll to the end of the list. Subtract
// the distance to the end focal keyline and then add the distance needed to let the last
// item hit the center of the end focal keyline.
int endScroll =
(int)
(lastItemDistanceFromFirstItem
- endFocalLocDistanceFromStart
+ (isRtl ? -1 : 1) * endFocalKeyline.maskedItemSize / 2F);
return isRtl ? min(0, endScroll) : max(0, endScroll);
}
/**
* Calculates the start of the child view item at {@code startPosition} in the end-to-end layout
* model.
*
* <p>This is used to calculate an initial point along the scroll axis from which to start looping
* over adapter items and calculating where children should be placed.
*
* @param startPosition the adapter position of the item whose start position will be calculated
* @return the start location of the view at {@code startPosition} along the scroll axis
*/
private float calculateChildStartForFill(int startPosition) {
float childScrollOffset = getParentStart() - scrollOffset;
float positionOffset = currentKeylineState.getItemSize() * startPosition;
return addEnd(childScrollOffset, positionOffset);
}
/**
* Remaps and returns the child's offset center from the end-to-end layout model.
*
* @param childCenterLocation the center of the child in the end-to-end layout model
* @param range the keyline range that the child is currently between
* @return the location along the scroll axis where the child should be located
*/
private float calculateChildOffsetCenterForLocation(
float childCenterLocation, KeylineRange range) {
float offsetCenter =
lerp(
range.leftOrTop.locOffset,
range.rightOrBottom.locOffset,
range.leftOrTop.loc,
range.rightOrBottom.loc,
childCenterLocation);
// If the current center is "out of bounds", meaning it is before the first keyline or after
// the last keyline, this item should begin scrolling at a fixed rate according to the
// last keyline it passed (either the first or last keyline).
// Compare reference equality here since there might be multiple keylines with the same
// values as the first/last keyline but we want to ensure this conditional is true only when
// we're working with the same object instance.
if (range.rightOrBottom == currentKeylineState.getFirstKeyline()
|| range.leftOrTop == currentKeylineState.getLastKeyline()) {
// Calculate how far past the nearest keyline (either the first or last keyline) this item
// has scrolled in the end-to-end layout. Then use that value calculate what would be a
// Keyline#locOffset.
float outOfBoundOffset =
(childCenterLocation - range.rightOrBottom.loc)
* (1F - range.rightOrBottom.mask);
offsetCenter += outOfBoundOffset;
}
return offsetCenter;
}
/**
* Gets the masked size of a child when its center is at {@code locOffset} and is between the
* given {@code range}.
*
* @param locOffset the offset location along the scrolling axis that should be within the keyline
* {@code range}
* @param range the keyline range that surrounds {@code locOffset}
* @return the masked size of a child when its center is at {@code locOffset} and is between the
* given {@code range}
*/
private float getMaskedItemSizeForLocOffset(float locOffset, KeylineRange range) {
return lerp(
range.leftOrTop.maskedItemSize,
range.rightOrBottom.maskedItemSize,
range.leftOrTop.locOffset,
range.rightOrBottom.locOffset,
locOffset);
}
/**
* Calculates and sets the child's mask according to its current location.
*
* @param child the child to mask
* @param childCenterLocation the center of the child in the end-to-end layout model
* @param range the keyline range that the child is currently between
*/
private void updateChildMaskForLocation(
View child, float childCenterLocation, KeylineRange range) {
if (!(child instanceof Maskable)) {
return;
}
// Interpolate the mask value based on the location of this view between it's two
// surrounding keylines.
float maskProgress =
lerp(
range.leftOrTop.mask,
range.rightOrBottom.mask,
range.leftOrTop.loc,
range.rightOrBottom.loc,
childCenterLocation);
float childHeight = child.getHeight();
float childWidth = child.getWidth();
// Translate the percentage into an actual pixel value of how much of this view should be
// masked away.
float maskWidth = lerp(0F, childWidth / 2F, 0F, 1F, maskProgress);
float maskHeight = lerp(0F, childHeight / 2F, 0F, 1F, maskProgress);
RectF maskRect = orientationHelper.getMaskRect(childHeight, childWidth, maskHeight, maskWidth);