Skip to content

Commit

Permalink
[Carousel] Force hero strategy to be start-aligned if there are not e…
Browse files Browse the repository at this point in the history
…nough items to make it center-aligned

Resolves #3626

PiperOrigin-RevId: 572641635
  • Loading branch information
imhappi authored and drchen committed Oct 12, 2023
1 parent be1395b commit 9a2347b
Showing 1 changed file with 26 additions and 5 deletions.
Expand Up @@ -49,7 +49,10 @@ public class HeroCarouselStrategy extends CarouselStrategy {

private static final int[] SMALL_COUNTS = new int[] {1};
private static final int[] MEDIUM_COUNTS = new int[] {0, 1};
private static final int MIN_ITEMS_FOR_CENTER_ALIGNMENT = 2;

// Current count of number of keylines. We want to refresh the strategy if there are less items
// than this number.
private int keylineCount = 0;

@Override
@NonNull
Expand Down Expand Up @@ -98,8 +101,7 @@ KeylineState onFirstChildMeasuredWithMargins(@NonNull Carousel carousel, @NonNul
largeCounts[i] = largeCountMin + i;
}
boolean isCenterAligned =
carousel.getCarouselAlignment() == CarouselLayoutManager.ALIGNMENT_CENTER
&& carousel.getItemCount() > MIN_ITEMS_FOR_CENTER_ALIGNMENT;
carousel.getCarouselAlignment() == CarouselLayoutManager.ALIGNMENT_CENTER;
Arrangement arrangement =
Arrangement.findLowestCostArrangement(
availableSpace,
Expand All @@ -115,6 +117,25 @@ KeylineState onFirstChildMeasuredWithMargins(@NonNull Carousel carousel, @NonNul
: MEDIUM_COUNTS,
targetLargeChildSize,
largeCounts);

keylineCount = arrangement.getItemCount();

// If there's less items than keylines, force it to be start-aligned.
if (arrangement.getItemCount() > carousel.getItemCount()) {
isCenterAligned = false;
arrangement =
Arrangement.findLowestCostArrangement(
availableSpace,
targetSmallChildSize,
smallChildSizeMin,
smallChildSizeMax,
smallCounts,
targetMediumChildSize,
MEDIUM_COUNTS,
targetLargeChildSize,
largeCounts);
}

return createKeylineState(
child.getContext(),
childMargins,
Expand All @@ -128,8 +149,8 @@ KeylineState onFirstChildMeasuredWithMargins(@NonNull Carousel carousel, @NonNul
@Override
boolean shouldRefreshKeylineState(@NonNull Carousel carousel, int oldItemCount) {
return carousel.getCarouselAlignment() == CarouselLayoutManager.ALIGNMENT_CENTER
&& (oldItemCount == MIN_ITEMS_FOR_CENTER_ALIGNMENT
|| carousel.getItemCount() == MIN_ITEMS_FOR_CENTER_ALIGNMENT);
&& ((oldItemCount < keylineCount && carousel.getItemCount() >= keylineCount)
|| (oldItemCount >= keylineCount && carousel.getItemCount() < keylineCount));
}
}

0 comments on commit 9a2347b

Please sign in to comment.