Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 121 additions & 25 deletions src/Controls/src/Core/Handlers/Items/Android/MauiCarouselRecyclerView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ public class MauiCarouselRecyclerView : MauiRecyclerView<CarouselView, ItemsView
int _oldPosition;
int _gotoPosition = -1;
int _scrollToCounter = 0;
int _currentItemUpdateCounter;
bool _noNeedForScroll;
bool _initialized;
bool _isVisible;
bool _disposed;
bool? _lastLoopValue;
bool _isInternalPositionUpdate;
bool _isUpdatingCurrentItem;
readonly float _touchSlop;
float _initialTouchX;
float _initialTouchY;
Expand Down Expand Up @@ -220,7 +222,7 @@ public override void UpdateAdapter()
if (oldItemViewAdapter != null && _initialized)
{
ItemsView.SetValueFromRenderer(CarouselView.PositionProperty, 0);
ItemsView.SetValueFromRenderer(CarouselView.CurrentItemProperty, null);
SetCurrentItemFromRenderer(null);
}

_gotoPosition = -1;
Expand Down Expand Up @@ -329,6 +331,7 @@ void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.
var currentItemPosition = observableItemsSource.GetPosition(Carousel.CurrentItem);
var count = observableItemsSource.Count;
var savedScrollToCounter = _scrollToCounter;
var savedCurrentItemUpdateCounter = _currentItemUpdateCounter;

// Equal-count Replace keeps the item count unchanged, so the position is preserved
// explicitly instead of relying on GetPosition(CurrentItem), which returns -1 for the
Expand All @@ -343,7 +346,7 @@ void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.

if (oldReplaceCount > 0 && oldReplaceCount == newReplaceCount)
{
HandleReplaceAction(e, carouselPosition, count, savedScrollToCounter, observableItemsSource);
HandleReplaceAction(e, carouselPosition, count, savedScrollToCounter, savedCurrentItemUpdateCounter, observableItemsSource);
return;
}

Expand Down Expand Up @@ -418,6 +421,8 @@ void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.
}
else if (Carousel.ItemsUpdatingScrollMode == ItemsUpdatingScrollMode.KeepItemsInView)
{
// Removing the current item falls back to the first item. A CurrentItem
// assignment made after this notification is handled in the dispatched callback.
carouselPosition = 0;
}

Expand All @@ -429,19 +434,15 @@ void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.
{
try
{
// If someone called explicit ScrollTo before the dispatched
// callback was delivered then don't override it.
if (_scrollToCounter == savedScrollToCounter)
bool scrollRequested = _scrollToCounter != savedScrollToCounter;
bool currentItemUpdated = _currentItemUpdateCounter != savedCurrentItemUpdateCounter;

// Do not let this deferred collection update override a ScrollTo or
// CurrentItem request made after the collection notification.
if (!scrollRequested && !currentItemUpdated)
{
SetCurrentItem(carouselPosition);
UpdatePosition(carouselPosition);
//If we are adding or removing the last item we need to update
//the inset that we give to items so they are centered
if (e.NewStartingIndex == count - 1 || removingLastElement)
{
UpdateItemDecoration();
}

if (Carousel.Loop)
{
UpdateLoopCentering(count);
Expand All @@ -450,15 +451,47 @@ void CollectionItemsSourceChanged(object sender, System.Collections.Specialized.
{
ScrollToPosition(carouselPosition);
}
}
else if (!scrollRequested && currentItemUpdated)
{
var updatedCurrentItemPosition =
ItemsViewAdapter.ItemsSource.GetPosition(Carousel.CurrentItem);

UpdateVisualStates();
if (updatedCurrentItemPosition >= 0)
{
_noNeedForScroll = true;
Carousel.SetValueFromRenderer(
CarouselView.PositionProperty,
updatedCurrentItemPosition);

if (Carousel.Loop)
{
UpdateLoopCentering(ItemsViewAdapter.ItemsSource.Count);
}
else
{
ScrollToItemPosition(
updatedCurrentItemPosition,
shouldAnimate: false);
}
}
}

// If we are adding or removing the last item we need to update
// the inset that we give to items so they are centered.
if (e.NewStartingIndex == count - 1 || removingLastElement)
{
UpdateItemDecoration();
}

UpdateVisualStates();
}
finally
{
// Reset flag after collection operations complete,
// always reset even if ScrollTo was called or an exception occurred
_isInternalPositionUpdate = false;
_noNeedForScroll = false;
}
});
}
Expand Down Expand Up @@ -504,7 +537,7 @@ internal void UpdateLoop()
Carousel.SetValueFromRenderer(CarouselView.PositionProperty, currentPosition);

var restoredItem = currentItem ?? ItemsViewAdapter.ItemsSource.GetItem(currentPosition);
Carousel.SetValueFromRenderer(CarouselView.CurrentItemProperty, restoredItem);
SetCurrentItemFromRenderer(restoredItem);
}
}

Expand All @@ -517,7 +550,7 @@ internal void UpdateLoop()
int loopedPosition = LoopedPosition(itemCount) + currentPosition;
ScrollToPosition(loopedPosition);
}
else
else
{
ScrollToPosition(currentPosition);
}
Expand Down Expand Up @@ -628,6 +661,7 @@ void HandleReplaceAction(
int carouselPosition,
int count,
int savedScrollToCounter,
int savedCurrentItemUpdateCounter,
IItemsViewSource observableItemsSource)
{
_noNeedForScroll = true;
Expand Down Expand Up @@ -685,12 +719,25 @@ void HandleReplaceAction(

if (_scrollToCounter == savedScrollToCounter)
{
// Position and the virtual scroll offset are unchanged, so we
// only refresh CurrentItem to the new value at the same position
// and update visual states. We must NOT ScrollToPosition here:
// the logical index maps to the start of the virtual range, which
// would jump the loop carousel away from its current location.
SetCurrentItem(carouselPosition);
if (_currentItemUpdateCounter != savedCurrentItemUpdateCounter)
{
var currentItemPosition = observableItemsSource.GetPosition(Carousel.CurrentItem);
if (currentItemPosition >= 0)
{
Carousel.SetValueFromRenderer(CarouselView.PositionProperty, currentItemPosition);
ScrollToItemPosition(currentItemPosition, shouldAnimate: false);
}
}
else
{
// Position and the virtual scroll offset are unchanged, so we
// only refresh CurrentItem to the new value at the same position.
// We must NOT ScrollToPosition here: the logical index maps to
// the start of the virtual range, which would jump the loop
// carousel away from its current location.
SetCurrentItem(carouselPosition);
}

UpdateVisualStates();
}
}
Expand Down Expand Up @@ -735,9 +782,22 @@ void HandleReplaceAction(
// callback was delivered then don't override it.
if (_scrollToCounter == savedScrollToCounter)
{
// Replace preserves the current position — no scroll needed.
SetCurrentItem(carouselPosition);
UpdatePosition(carouselPosition);
if (_currentItemUpdateCounter != savedCurrentItemUpdateCounter)
{
var currentItemPosition = observableItemsSource.GetPosition(Carousel.CurrentItem);
if (currentItemPosition >= 0)
{
Carousel.SetValueFromRenderer(CarouselView.PositionProperty, currentItemPosition);
ScrollToItemPosition(currentItemPosition, shouldAnimate: false);
}
}
else
{
// Replace preserves the current position — no scroll needed.
SetCurrentItem(carouselPosition);
UpdatePosition(carouselPosition);
}

UpdateVisualStates();
}
}
Expand Down Expand Up @@ -926,11 +986,47 @@ void SetCurrentItem(int carouselPosition)
return;

var item = ItemsViewAdapter.ItemsSource.GetItem(carouselPosition);
Carousel.SetValueFromRenderer(CarouselView.CurrentItemProperty, item);
SetCurrentItemFromRenderer(item);
}

void SetCurrentItemFromRenderer(object item)
{
var carousel = Carousel;
var wasUpdatingCurrentItem = _isUpdatingCurrentItem;
_isUpdatingCurrentItem = true;
try
{
carousel.SetValueFromRenderer(CarouselView.CurrentItemProperty, item);
}
finally
{
_isUpdatingCurrentItem = wasUpdatingCurrentItem;
}

// BindableObject drains nested assignments before the setter returns.
// Replay an application selection after renderer synchronization finishes.
if (!wasUpdatingCurrentItem && ReferenceEquals(Carousel, carousel)
&& !Equals(carousel.CurrentItem, item))
{
((IMauiCarouselRecyclerView)this).UpdateFromCurrentItem();
}
}

void IMauiCarouselRecyclerView.UpdateFromCurrentItem()
{
// Renderer synchronization is not a new application selection.
if (_isUpdatingCurrentItem)
{
return;
}

_currentItemUpdateCounter++;

if (_isInternalPositionUpdate)
Comment thread
Dhivya-SF4094 marked this conversation as resolved.
Resolved
{
return;
Comment on lines +1025 to +1027
}

var currentItemPosition = ItemsViewAdapter.ItemsSource.GetPosition(Carousel.CurrentItem);
var carouselPosition = Carousel.Position;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
using Microsoft.Maui.Handlers;
using Microsoft.Maui.Platform;
using Xunit;
using static Microsoft.Maui.DeviceTests.AssertHelpers;

namespace Microsoft.Maui.DeviceTests
{
Expand Down Expand Up @@ -104,6 +105,88 @@ await CreateHandlerAndAddToWindow<CarouselViewHandler>(carouselView, async (hand
});
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SelectingCurrentItemInsideCurrentItemChangedUpdatesRenderedItem(bool loop)
{
SetupBuilder();

var items = new[] { "A", "B", "C" };
var carouselView = new CarouselView
{
ItemsSource = items,
Loop = loop,
IsScrollAnimated = false,
ItemTemplate = new DataTemplate(() =>
{
var label = new Label();
label.SetBinding(Label.TextProperty, ".");
return label;
})
};

await CreateHandlerAndAddToWindow<CarouselViewHandler>(carouselView, async handler =>
{
var recyclerView = handler.PlatformView;
await recyclerView.WaitForLayoutOrNonZeroSize();

Label GetCenteredLabel()
{
var cell = recyclerView.FindChildViewUnder(
recyclerView.Width / 2f, recyclerView.Height / 2f) as ItemContentView;
return cell?.View as Label;
}

await AssertEventually(
() => carouselView.Position == 0
&& Equals(carouselView.CurrentItem, items[0])
&& Equals(GetCenteredLabel()?.BindingContext, items[0]),
message: "The carousel should initially display A.");

bool redirected = false;
carouselView.CurrentItemChanged += (_, args) =>
{
if (!redirected && Equals(args.CurrentItem, items[1]))
{
redirected = true;
carouselView.CurrentItem = items[2];
}
};

// Use the next native adapter position, including the virtual range in loop mode.
// This exercises renderer synchronization without a MAUI ScrollTo request in flight.
var initialCell = recyclerView.FindChildViewUnder(
recyclerView.Width / 2f, recyclerView.Height / 2f);
Assert.NotNull(initialCell);
var initialAdapterPosition = recyclerView.GetChildAdapterPosition(initialCell);
Assert.NotEqual(RecyclerView.NoPosition, initialAdapterPosition);
recyclerView.SmoothScrollToPosition(initialAdapterPosition + 1);

var synchronized = await Wait(
() => redirected
&& Equals(carouselView.CurrentItem, items[2])
&& carouselView.Position == 2
&& recyclerView.ScrollState == RecyclerView.ScrollStateIdle
&& Equals(GetCenteredLabel()?.BindingContext, items[2])
&& GetCenteredLabel()?.Text == items[2]);

var finalLabel = GetCenteredLabel();
Assert.True(synchronized,
$"Loop={loop}, Redirected={redirected}, CurrentItem={carouselView.CurrentItem}, " +
$"Position={carouselView.Position}, ScrollState={recyclerView.ScrollState}, " +
$"CenteredItem={finalLabel?.BindingContext}, RenderedText={finalLabel?.Text}. " +
"Expected CurrentItem C, Position 2, and C rendered at the center after scrolling settles.");

Assert.True(redirected);
Assert.Equal(items[2], carouselView.CurrentItem);
Assert.Equal(2, carouselView.Position);
var centeredLabel = Assert.IsType<Label>(GetCenteredLabel());
Assert.Equal(items[2], centeredLabel.BindingContext);
Assert.Equal(items[2], centeredLabel.Text);
});
}

class CarouselItem
{
public CarouselItem(int index) => Index = index;
Expand Down
Loading
Loading