diff --git a/src/Controls/src/Core/Handlers/Items/Android/DataChangeObserver.cs b/src/Controls/src/Core/Handlers/Items/Android/DataChangeObserver.cs index 31ad84f46812..4862db5334fc 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/DataChangeObserver.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/DataChangeObserver.cs @@ -10,12 +10,19 @@ internal class DataChangeObserver : RecyclerView.AdapterDataObserver { IntPtr _adapter; readonly Action _onDataChange; + readonly Func _lastRowSize; public bool Observing { get; private set; } - public DataChangeObserver(Action onDataChange) : base() + // Only used with lastRowSize: the adapter's item count as of the last layout pass, kept up to date with the insertions + // and removals since then, or -1 when unknown + public int ItemCount { get; set; } = -1; + + // lastRowSize: when set, only report items inserted into or removed from the last row (that many positions, 0 for none) + public DataChangeObserver(Action onDataChange, Func lastRowSize = null) : base() { _onDataChange = onDataChange; + _lastRowSize = lastRowSize; } public void Start(Adapter adapter) @@ -28,6 +35,7 @@ public void Start(Adapter adapter) adapter.RegisterAdapterDataObserver(this); _adapter = adapter.Handle; + ItemCount = -1; Observing = true; } @@ -45,37 +53,80 @@ public void Stop(Adapter adapter) public override void OnChanged() { base.OnChanged(); - _onDataChange?.Invoke(); + ItemCount = -1; + + if (_lastRowSize is null) + { + _onDataChange?.Invoke(); + } } public override void OnItemRangeInserted(int positionStart, int itemCount) { base.OnItemRangeInserted(positionStart, itemCount); - _onDataChange?.Invoke(); + + if (ItemCount >= 0) + { + ItemCount += itemCount; + } + + if (_lastRowSize is null || ReachesLastRow(positionStart + itemCount)) + { + _onDataChange?.Invoke(); + } } public override void OnItemRangeChanged(int positionStart, int itemCount) { base.OnItemRangeChanged(positionStart, itemCount); - _onDataChange?.Invoke(); + + if (_lastRowSize is null) + { + _onDataChange?.Invoke(); + } } public override void OnItemRangeChanged(int positionStart, int itemCount, Object payload) { base.OnItemRangeChanged(positionStart, itemCount, payload); - _onDataChange?.Invoke(); + + if (_lastRowSize is null) + { + _onDataChange?.Invoke(); + } } public override void OnItemRangeRemoved(int positionStart, int itemCount) { base.OnItemRangeRemoved(positionStart, itemCount); - _onDataChange?.Invoke(); + + if (ItemCount >= 0) + { + ItemCount -= itemCount; + } + + if (_lastRowSize is null || ReachesLastRow(positionStart)) + { + _onDataChange?.Invoke(); + } } public override void OnItemRangeMoved(int fromPosition, int toPosition, int itemCount) { base.OnItemRangeMoved(fromPosition, toPosition, itemCount); - _onDataChange?.Invoke(); + + if (_lastRowSize is null) + { + _onDataChange?.Invoke(); + } + } + + // True when a range ending at `position` (exclusive) reaches the last row. Without a count from a layout pass yet, + // report the change rather than risk stale spacing. + bool ReachesLastRow(int position) + { + int lastRowSize = _lastRowSize(); + return lastRowSize > 0 && (ItemCount < 0 || position > ItemCount - lastRowSize); } bool IsValidAdapter(Adapter adapter) diff --git a/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs b/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs index dc3cbce9b637..5538f93b65be 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs @@ -39,6 +39,7 @@ public class MauiRecyclerView : Recycler EmptyViewAdapter _emptyViewAdapter; readonly DataChangeObserver _emptyCollectionObserver; readonly DataChangeObserver _itemsUpdateScrollObserver; + readonly DataChangeObserver _itemSpacingObserver; readonly Func _dispatchTouchEventToRecyclerView; ParentScrollGestureDispatcher _parentScrollGestureDispatcher; @@ -62,6 +63,9 @@ public MauiRecyclerView(Context context, Func getItemsLayout, Func _emptyCollectionObserver = new DataChangeObserver(UpdateEmptyViewVisibility); _itemsUpdateScrollObserver = new DataChangeObserver(AdjustScrollForItemUpdate); + // RecyclerView recomputes the offsets of items it rebinds or shifts (and of every item on a full reset), so only + // insertions and removals in the last row can leave items that kept their position with stale edge spacing + _itemSpacingObserver = new DataChangeObserver(InvalidateItemSpacing, GetSpacingLastRowSize); _dispatchTouchEventToRecyclerView = DispatchTouchEventToRecyclerView; _parentScrollGestureDispatcher = new ParentScrollGestureDispatcher(this); } @@ -152,6 +156,7 @@ public virtual void TearDownOldElement(TItemsView oldElement) // Stop watching for empty items or scroll adjustments _emptyCollectionObserver.Stop(ItemsViewAdapter); _itemsUpdateScrollObserver.Stop(ItemsViewAdapter); + _itemSpacingObserver.Stop(ItemsViewAdapter); // Unhook whichever adapter is active SetAdapter(null); @@ -308,8 +313,10 @@ public virtual void UpdateAdapter() var oldItemViewAdapter = ItemsViewAdapter; _emptyCollectionObserver.Stop(oldItemViewAdapter); + _itemSpacingObserver.Stop(oldItemViewAdapter); ItemsViewAdapter = CreateAdapter(); + _itemSpacingObserver.Start(ItemsViewAdapter); (RecyclerViewScrollListener as RecyclerViewScrollListener)?.UpdateAdapter(ItemsViewAdapter); @@ -628,6 +635,24 @@ protected virtual ItemDecoration CreateSpacingDecoration(IItemsLayout itemsLayou return new SpacingItemDecoration(Context, itemsLayout); } + // Only the spacing along the scrolling direction depends on an item's position; the cross-axis spacing is the same for every item + bool HasPositionDependentSpacing() => + _itemDecoration is SpacingItemDecoration spacing + && ((ItemsLayout as ItemsLayout)?.Orientation == ItemsLayoutOrientation.Horizontal ? spacing.HorizontalOffset : spacing.VerticalOffset) != 0; + + // The number of positions in the last row whose edge spacing can change, or 0 when no spacing depends on the position + int GetSpacingLastRowSize() => HasPositionDependentSpacing() ? (ItemsLayout is GridItemsLayout grid ? grid.Span : 1) : 0; + + void InvalidateItemSpacing() + { + // SpacingItemDecoration drops the spacing on the outer edges based on each item's position, but RecyclerView only + // recomputes the offsets of items it rebinds or shifts (not the previous last item on an append, for example) + if (!IsComputingLayout) + { + InvalidateItemDecorations(); + } + } + protected virtual void ReconcileFlowDirectionAndLayout() { if (!(GetLayoutManager() is LinearLayoutManager linearLayoutManager)) @@ -711,6 +736,10 @@ protected override void OnLayout(bool changed, int l, int t, int r, int b) { base.OnLayout(changed, l, t, r, b); ClipBounds = new ARect(0, 0, Width, Height); + + // The count this layout pass used (ItemCount walks every group of a grouped source, so read it once here rather than + // for every notification); the spacing observer applies the insertions and removals until the next layout pass + _itemSpacingObserver.ItemCount = HasPositionDependentSpacing() ? ItemsViewAdapter?.ItemCount ?? 0 : -1; // After a direct (non-animated) scroll operation, we may need to make adjustments // to align the target item; if an adjustment is pending, execute it here. // (Deliberately checking the private member here rather than the property accessor; the accessor will diff --git a/src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs b/src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs index 53ed2a59cf68..7de905ddc107 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs @@ -105,7 +105,7 @@ public override void GetItemOffsets(ARect outRect, AView view, RecyclerView pare var spanSizeLookup = gridLayoutManager.GetSpanSizeLookup(); int spanCount = gridLayoutManager.SpanCount; isInFirstRowCol = IsInFirstSpanGroup(spanSizeLookup, position, spanCount); - isInLastRowCol = IsInLastSpanGroup(spanSizeLookup, view, position, itemCount, spanCount); + isInLastRowCol = IsInLastSpanGroup(spanSizeLookup, view, state, position, itemCount, spanCount); } else { @@ -156,7 +156,7 @@ static bool IsInFirstSpanGroup(GridLayoutManager.SpanSizeLookup spanSizeLookup, return true; } - static bool IsInLastSpanGroup(GridLayoutManager.SpanSizeLookup spanSizeLookup, AView view, int position, int itemCount, int spanCount) + static bool IsInLastSpanGroup(GridLayoutManager.SpanSizeLookup spanSizeLookup, AView view, RecyclerView.State state, int position, int itemCount, int spanCount) { // Every item occupies at least one span, so the last row holds at most spanCount items. if (itemCount - 1 - position >= spanCount) @@ -164,7 +164,7 @@ static bool IsInLastSpanGroup(GridLayoutManager.SpanSizeLookup spanSizeLookup, A return false; } - int span = GetSpanIndex(spanSizeLookup, view, position, spanCount) + spanSizeLookup.GetSpanSize(position); + int span = GetSpanIndex(spanSizeLookup, view, state, position, spanCount) + spanSizeLookup.GetSpanSize(position); for (int i = position + 1; i < itemCount; i++) { @@ -182,11 +182,13 @@ static bool IsInLastSpanGroup(GridLayoutManager.SpanSizeLookup spanSizeLookup, A return true; } - static int GetSpanIndex(GridLayoutManager.SpanSizeLookup spanSizeLookup, AView view, int position, int spanCount) + static int GetSpanIndex(GridLayoutManager.SpanSizeLookup spanSizeLookup, AView view, RecyclerView.State state, int position, int spanCount) { // GridLayoutManager assigns spans to the whole row before measuring its children, so the // LayoutParams already hold the answer; fall back to the lookup for anything not yet assigned. - if (view.LayoutParameters is GridLayoutManager.LayoutParams layoutParams + // In pre-layout they hold the span of the item's old position, which no longer matches `position`. + if (!state.IsPreLayout + && view.LayoutParameters is GridLayoutManager.LayoutParams layoutParams && layoutParams.SpanIndex != GridLayoutManager.LayoutParams.InvalidSpanId) { return layoutParams.SpanIndex; diff --git a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs index 75e4545a9535..388c17715f2b 100644 --- a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs +++ b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs @@ -213,6 +213,340 @@ await CreateHandlerAndAddToWindow(host, async _ => }); } + [Theory(DisplayName = "ItemSpacing matches an up-front list after items are added, removed or replaced at runtime")] + [InlineData(false, "Append")] + [InlineData(false, "InsertAtStart")] + [InlineData(false, "RemoveFromEnd")] + [InlineData(false, "RemoveFromStart")] + [InlineData(false, "Replace")] + [InlineData(true, "Append")] + [InlineData(true, "InsertAtStart")] + [InlineData(true, "RemoveFromEnd")] + [InlineData(true, "RemoveFromStart")] + [InlineData(true, "Replace")] + public async Task ItemSpacingIsUpdatedWhenItemsChangeAtRuntime(bool grid, string change) + { + SetupBuilder(); + + var finalItems = grid ? new[] { "0", "1", "2", "3" } : new[] { "0", "1", "2" }; + + var collectionView = new CollectionView + { + ItemsLayout = grid + ? new GridItemsLayout(2, ItemsLayoutOrientation.Vertical) { VerticalItemSpacing = 8 } + : new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { ItemSpacing = 8 }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + }; + + // The CollectionView sizes to its content here, so spacing left on an outer edge shows up in its height + var layout = new VerticalStackLayout { collectionView }; + + await CreateHandlerAndAddToWindow(layout, async _ => + { + var recyclerView = (RecyclerView)collectionView.Handler.PlatformView; + + collectionView.ItemsSource = new ObservableCollection(finalItems); + var expected = await GetSettledItemLayout(recyclerView, finalItems.Length); + + var items = new ObservableCollection(change switch + { + "Append" => finalItems.Take(grid ? 2 : 1), + "InsertAtStart" => finalItems.Skip(1), + "RemoveFromEnd" => finalItems.Append("extra"), + "RemoveFromStart" => finalItems.Prepend("extra"), + _ => finalItems.Select((item, index) => index == 1 ? "replaced" : item), + }); + collectionView.ItemsSource = items; + await GetSettledItemLayout(recyclerView, items.Count); + + switch (change) + { + case "Append": + while (items.Count < finalItems.Length) + { + items.Add(finalItems[items.Count]); + await GetSettledItemLayout(recyclerView, items.Count); + } + break; + case "InsertAtStart": + items.Insert(0, finalItems[0]); + break; + case "RemoveFromEnd": + items.RemoveAt(items.Count - 1); + break; + case "RemoveFromStart": + items.RemoveAt(0); + break; + default: + items[1] = finalItems[1]; + break; + } + + Assert.Equal(expected, await GetSettledItemLayout(recyclerView, finalItems.Length)); + }); + + static async Task GetSettledItemLayout(RecyclerView recyclerView, int itemCount) + { + await AssertEventually(() => recyclerView.ChildCount == itemCount && !recyclerView.IsAnimating && !recyclerView.IsLayoutRequested, timeout: 5000); + + var tops = new int[itemCount]; + for (var i = 0; i < itemCount; i++) + { + var child = recyclerView.GetChildAt(i); + tops[recyclerView.GetChildAdapterPosition(child)] = child.Top; + } + + return $"item tops [{string.Join(", ", tops)}], height {recyclerView.Height}"; + } + } + + [Fact(DisplayName = "Replacing an off-screen item does not recompute the spacing of the visible items")] + public async Task ReplacingAnItemDoesNotRecomputeOtherItemOffsets() + { + SetupBuilder(); + + var items = new ObservableCollection(Enumerable.Range(0, 100).Select(i => $"{i}")); + var collectionView = new CollectionView + { + ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { ItemSpacing = 8 }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + ItemsSource = items, + }; + + await CreateHandlerAndAddToWindow(collectionView, async handler => + { + var recyclerView = handler.PlatformView; + var offsets = new ItemOffsetsCounter(); + recyclerView.AddItemDecoration(offsets); + await AssertEventually(() => offsets.Count > 0 && !recyclerView.IsLayoutRequested); + + offsets.Count = 0; + items[items.Count - 1] = "replaced"; + await AssertEventually(() => !recyclerView.IsLayoutRequested); + + // RecyclerView only recomputes the offsets of children whose decorations were invalidated + Assert.Equal(0, offsets.Count); + }); + } + + [Theory(DisplayName = "The ItemSpacing observer only reports insertions and removals in the last row")] + [InlineData("Insert", 0, 1, false)] + [InlineData("Insert", 98, 1, false)] + [InlineData("Insert", 99, 1, true)] + [InlineData("Remove", 0, 1, false)] + [InlineData("Remove", 99, 1, false)] + [InlineData("Remove", 100, 1, true)] + [InlineData("Change", 99, 1, false)] + [InlineData("Move", 99, 0, false)] + [InlineData("Reset", 0, 0, false)] + public void ItemSpacingObserverOnlyReportsLastRowChanges(string change, int positionStart, int itemCount, bool expected) + { + var calls = 0; + + // ItemCount is the count at the last layout pass; the change leaves 100 items in a list, so the last row starts at 99 + using var observer = new DataChangeObserver(() => calls++, () => 1) + { + ItemCount = change switch { "Insert" => 100 - itemCount, "Remove" => 100 + itemCount, _ => 100 }, + }; + + switch (change) + { + case "Insert": + observer.OnItemRangeInserted(positionStart, itemCount); + break; + case "Remove": + observer.OnItemRangeRemoved(positionStart, itemCount); + break; + case "Change": + observer.OnItemRangeChanged(positionStart, itemCount); + break; + case "Move": + observer.OnItemRangeMoved(positionStart, itemCount, 1); + break; + default: + observer.OnChanged(); + break; + } + + Assert.Equal(expected ? 1 : 0, calls); + } + + [Fact(DisplayName = "The ItemSpacing observer applies every change since the last layout pass")] + public void ItemSpacingObserverAppliesChangesSinceLastLayout() + { + var calls = 0; + + // One item at the last layout pass, then two appends dispatched before the next one + using var observer = new DataChangeObserver(() => calls++, () => 1) { ItemCount = 1 }; + observer.OnItemRangeInserted(1, 1); + observer.OnItemRangeInserted(2, 1); + Assert.Equal(2, calls); + + observer.OnItemRangeInserted(0, 1); + observer.OnItemRangeRemoved(3, 1); + Assert.Equal(3, calls); + Assert.Equal(3, observer.ItemCount); + + // A reset can change the count in any way, so changes are reported until the next layout pass sets it again + observer.OnChanged(); + observer.OnItemRangeInserted(0, 1); + Assert.Equal(4, calls); + } + + [Fact(DisplayName = "Inserting into the first group of a grouped CollectionView with item spacing does not count all groups")] + public async Task GroupedInsertWithItemSpacingDoesNotCountAllGroups() + { + SetupBuilder(); + + var groups = Enumerable.Range(0, 5).Select(g => new EnumerationCountingGroup(Enumerable.Range(0, 3).Select(i => $"{g}-{i}"))).ToList(); + var collectionView = new CollectionView + { + IsGrouped = true, + ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { ItemSpacing = 8 }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + ItemsSource = groups, + }; + + await CreateHandlerAndAddToWindow(collectionView, async handler => + { + var recyclerView = handler.PlatformView; + await AssertEventually(() => recyclerView.ChildCount > 0 && !recyclerView.IsLayoutRequested); + + var lastGroup = groups[groups.Count - 1]; + lastGroup.Enumerations = 0; + groups[0].Add("new"); + + // The notification uses the count from the last layout pass instead of counting every group again + Assert.Equal(0, lastGroup.Enumerations); + }); + } + + [Theory(DisplayName = "Inserting or removing an off-screen middle item does not recompute the spacing of the visible items")] + [InlineData(true)] + [InlineData(false)] + public async Task OffscreenMiddleChangeDoesNotRecomputeOffsets(bool insert) + { + SetupBuilder(); + + var items = new ObservableCollection(Enumerable.Range(0, 100).Select(i => $"{i}")); + var collectionView = new CollectionView + { + ItemsLayout = new LinearItemsLayout(ItemsLayoutOrientation.Vertical) { ItemSpacing = 8 }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + ItemsSource = items, + }; + + await CreateHandlerAndAddToWindow(collectionView, async handler => + { + var recyclerView = handler.PlatformView; + var offsets = new ItemOffsetsCounter(); + recyclerView.AddItemDecoration(offsets); + await AssertEventually(() => offsets.Count > 0 && !recyclerView.IsLayoutRequested); + + offsets.Count = 0; + if (insert) + items.Insert(50, "new"); + else + items.RemoveAt(50); + await AssertEventually(() => !recyclerView.IsLayoutRequested); + + // The count from the last layout pass shows the change is far from the last row, so nothing is invalidated + Assert.Equal(0, offsets.Count); + }); + } + + [Fact(DisplayName = "Appending to a grid with only cross-axis spacing does not recompute the spacing of the visible items")] + public async Task AppendingToGridWithCrossAxisSpacingDoesNotRecomputeOffsets() + { + SetupBuilder(); + + var items = new ObservableCollection(Enumerable.Range(0, 100).Select(i => $"{i}")); + var collectionView = new CollectionView + { + ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical) { HorizontalItemSpacing = 8 }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + ItemsSource = items, + }; + + await CreateHandlerAndAddToWindow(collectionView, async handler => + { + var recyclerView = handler.PlatformView; + var offsets = new ItemOffsetsCounter(); + recyclerView.AddItemDecoration(offsets); + await AssertEventually(() => offsets.Count > 0 && !recyclerView.IsLayoutRequested); + + offsets.Count = 0; + items.Add("new"); + await AssertEventually(() => !recyclerView.IsLayoutRequested); + + // HorizontalItemSpacing is the same for every row, so the off-screen append changes no visible item's spacing + Assert.Equal(0, offsets.Count); + }); + } + + [Theory(DisplayName = "Inserting into a grouped CollectionView without scrolling-axis spacing does not count all groups")] + [InlineData(0)] + [InlineData(8)] + public async Task GroupedInsertWithoutScrollingAxisSpacingDoesNotCountAllGroups(double crossAxisSpacing) + { + SetupBuilder(); + + var groups = Enumerable.Range(0, 5).Select(g => new EnumerationCountingGroup(Enumerable.Range(0, 3).Select(i => $"{g}-{i}"))).ToList(); + var collectionView = new CollectionView + { + IsGrouped = true, + ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical) { HorizontalItemSpacing = crossAxisSpacing }, + ItemTemplate = new DataTemplate(() => new Label { HeightRequest = 30 }), + ItemsSource = groups, + }; + + await CreateHandlerAndAddToWindow(collectionView, async handler => + { + var recyclerView = handler.PlatformView; + await AssertEventually(() => recyclerView.ChildCount > 0 && !recyclerView.IsLayoutRequested); + + var lastGroup = groups[groups.Count - 1]; + lastGroup.Enumerations = 0; + groups[0].Add("new"); + + // Counting the items (ItemsViewAdapter.ItemCount) walks every group, so it would enumerate the last group + Assert.Equal(0, lastGroup.Enumerations); + }); + } + + class EnumerationCountingGroup : IEnumerable, System.Collections.Specialized.INotifyCollectionChanged + { + readonly List _items; + + public EnumerationCountingGroup(IEnumerable items) => _items = new List(items); + + public int Enumerations { get; set; } + + public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; + + public void Add(string item) + { + _items.Add(item); + CollectionChanged?.Invoke(this, new System.Collections.Specialized.NotifyCollectionChangedEventArgs( + System.Collections.Specialized.NotifyCollectionChangedAction.Add, item, _items.Count - 1)); + } + + public IEnumerator GetEnumerator() + { + Enumerations++; + return _items.GetEnumerator(); + } + + System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator(); + } + + class ItemOffsetsCounter : RecyclerView.ItemDecoration + { + public int Count { get; set; } + + public override void GetItemOffsets(global::Android.Graphics.Rect outRect, AView view, RecyclerView parent, RecyclerView.State state) => Count++; + } + [Fact] public async Task GroupedCollectionViewEmptyViewTracksOuterGroupCount() { diff --git a/src/Core/tests/Benchmarks.Droid/CollectionViewItemSpacingBenchmark.cs b/src/Core/tests/Benchmarks.Droid/CollectionViewItemSpacingBenchmark.cs new file mode 100644 index 000000000000..d1c28c661a44 --- /dev/null +++ b/src/Core/tests/Benchmarks.Droid/CollectionViewItemSpacingBenchmark.cs @@ -0,0 +1,127 @@ +using System.Collections.ObjectModel; +using Android.Views; +using AndroidX.RecyclerView.Widget; +using Microsoft.Maui; +using Microsoft.Maui.Controls; +using Microsoft.Maui.Controls.Handlers.Items; +using Microsoft.Maui.Handlers; +using Microsoft.Maui.Hosting; +using Microsoft.Maui.Platform; + +namespace Benchmarks.Droid; + +// Measures collection changes on an Android CollectionView with and without ItemSpacing. Each operation changes +// the items, runs a synchronous layout pass, reverts the change and lays out again, so every iteration starts from +// the same state. Everything runs on the main thread because CollectionView dispatches collection changes there. +public class CollectionViewItemSpacingBenchmark +{ + const int ItemCount = 50; + const int Width = 1080; + const int Height = 1920; + const int Operations = 20; + + ObservableCollection _spacedItems = null!; + ObservableCollection _unspacedItems = null!; + ObservableCollection _gridItems = null!; + Android.Views.View _spacedView = null!; + Android.Views.View _unspacedView = null!; + Android.Views.View _gridView = null!; + + [GlobalSetup] + public void GlobalSetup() => RunOnMain(() => + { + var app = MauiApp.CreateBuilder() + .ConfigureMauiHandlers(handlers => + { + handlers.AddHandler(_ => new CollectionViewHandler()); + handlers.AddHandler