diff --git a/src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs b/src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs index 846a9a0d07d9..c4052aadb257 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs @@ -44,7 +44,7 @@ public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int positi _currentViewHolders.Add(selectable); // Make sure that if this item is one of the selected items, it's marked as selected - selectable.IsSelected = PositionIsSelected(position); + selectable.UpdateIsSelected(PositionIsSelected(position)); } public override void OnViewRecycled(Object holder) @@ -53,7 +53,7 @@ public override void OnViewRecycled(Object holder) { _currentViewHolders.Remove(selectable); selectable.Clicked -= SelectableClicked; - selectable.IsSelected = false; + selectable.UpdateIsSelected(false); } base.OnViewRecycled(holder); diff --git a/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs b/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs index b28b39d1e10f..13ebe5e44eac 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs @@ -749,16 +749,28 @@ protected virtual void UpdateItemSpacing() if (_itemDecoration != null) { RemoveItemDecoration(_itemDecoration); + _itemDecoration = null; } - _itemDecoration = CreateSpacingDecoration(ItemsLayout); - AddItemDecoration(_itemDecoration); + var itemDecoration = CreateSpacingDecoration(ItemsLayout); - if (_itemDecoration is SpacingItemDecoration spacingDecoration) + if (itemDecoration is SpacingItemDecoration spacingDecoration) { // Outer-edge spacing handled by SpacingItemDecoration.GetItemOffsets for all layout types. SetPadding(0, 0, 0, 0); + + // Without spacing it would offset nothing, but RecyclerView would still call its GetItemOffsets for every + // item it lays out. A subclass might offset items on its own. + if (spacingDecoration.HorizontalOffset == 0 && spacingDecoration.VerticalOffset == 0 + && spacingDecoration.GetType() == typeof(SpacingItemDecoration)) + { + spacingDecoration.Dispose(); + return; + } } + + _itemDecoration = itemDecoration; + AddItemDecoration(_itemDecoration); } protected virtual ItemDecoration CreateSpacingDecoration(IItemsLayout itemsLayout) diff --git a/src/Controls/src/Core/Handlers/Items/Android/SelectableViewHolder.cs b/src/Controls/src/Core/Handlers/Items/Android/SelectableViewHolder.cs index 3dce2b8de830..dac9ab96297b 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/SelectableViewHolder.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/SelectableViewHolder.cs @@ -12,6 +12,8 @@ namespace Microsoft.Maui.Controls.Handlers.Items public abstract class SelectableViewHolder : RecyclerView.ViewHolder, global::Android.Views.View.IOnClickListener { bool _isSelected; + // Whether the item view and its content show _isSelected; see UpdateIsSelected. + bool _isSelectionApplied; Drawable _selectedDrawable; Drawable _selectableItemDrawable; bool _isSelectionEnabled; @@ -46,6 +48,7 @@ public bool IsSelected set { _isSelected = value; + _isSelectionApplied = true; SetSelectionStates(_isSelected); @@ -55,6 +58,28 @@ public bool IsSelected } } + /// + /// Sets , unless the item view and its content already show . + /// + /// + /// The adapter sets the selection of every item it binds or recycles, and with selection off it is always false: + /// applying a value the item already shows would only repeat four calls into Java. + /// + internal void UpdateIsSelected(bool isSelected) + { + if (_isSelectionApplied && _isSelected == isSelected) + { + return; + } + + IsSelected = isSelected; + } + + /// + /// Makes the next apply the selection, because the item's content has been replaced. + /// + internal void InvalidateIsSelected() => _isSelectionApplied = false; + protected virtual bool UseDefaultSelectionColor => true; public void OnClick(global::Android.Views.View view) diff --git a/src/Controls/src/Core/Handlers/Items/Android/TemplatedItemViewHolder.cs b/src/Controls/src/Core/Handlers/Items/Android/TemplatedItemViewHolder.cs index 94d0345ac1c7..2d91c7d366e2 100644 --- a/src/Controls/src/Core/Handlers/Items/Android/TemplatedItemViewHolder.cs +++ b/src/Controls/src/Core/Handlers/Items/Android/TemplatedItemViewHolder.cs @@ -74,6 +74,10 @@ public void Bind(object itemBindingContext, ItemsView itemsView, _itemContentView.RealizeContent(View, itemsView); _selectedTemplate = template; + + // The new content isn't selected yet, and its visual states decide whether the item view shows the + // default selection color. + InvalidateIsSelected(); } _itemContentView.HandleItemSizingStrategy(reportMeasure, size); diff --git a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs index 654e9cd7a91e..5c725c7b03f9 100644 --- a/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs +++ b/src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs @@ -90,6 +90,9 @@ void AssertChildBounds(int spacing) MeasureAndLayout(); AssertChildBounds(0); + // Without spacing, there is no decoration whose offsets RecyclerView would ask for every item. + Assert.Equal(0, recyclerView.ItemDecorationCount); + double requestedSpacing = recyclerView.Context.FromPixels(40); // Android truncates each half-gap separately; derive the expected pixel gap // from density conversion rather than assuming a dp/pixel round trip is exact. @@ -102,6 +105,7 @@ void AssertChildBounds(int spacing) // Do not construct a decoration or manually invalidate decoration/size caches. MeasureAndLayout(); AssertChildBounds(expectedSpacing); + Assert.Equal(1, recyclerView.ItemDecorationCount); if (orientation == ItemsLayoutOrientation.Vertical) { @@ -113,6 +117,13 @@ void AssertChildBounds(int spacing) MeasureAndLayout(); AssertChildBounds(expectedSpacing); } + + // Removing the spacing again removes the decoration and its gaps. + layout.HorizontalItemSpacing = 0; + layout.VerticalItemSpacing = 0; + MeasureAndLayout(); + AssertChildBounds(0); + Assert.Equal(0, recyclerView.ItemDecorationCount); }); } @@ -765,6 +776,223 @@ await InvokeOnMainThreadAsync(() => }); } + [Theory(DisplayName = "Recycled CollectionView items show the selection of the item they are bound to")] + [InlineData(SelectionMode.Single, false)] + [InlineData(SelectionMode.Multiple, false)] + [InlineData(SelectionMode.Single, true)] + [InlineData(SelectionMode.Multiple, true)] + public async Task RecycledItemsShowTheirOwnSelection(SelectionMode selectionMode, bool templateColorsSelection) + { + SetupBuilder(); + + await InvokeOnMainThreadAsync(() => + { + var items = Enumerable.Range(0, 60).Select(i => $"Item {i}").ToArray(); + var collectionView = new CollectionView + { + SelectionMode = selectionMode, + ItemTemplate = new DataTemplate(() => + { + var label = new Label { HeightRequest = 40 }; + label.SetBinding(Label.TextProperty, "."); + + if (templateColorsSelection) + { + var selected = new VisualState { Name = VisualStateManager.CommonStates.Selected }; + selected.Setters.Add(new Setter { Property = VisualElement.BackgroundColorProperty, Value = Colors.Orange }); + var commonStates = new VisualStateGroup { Name = nameof(VisualStateManager.CommonStates) }; + commonStates.States.Add(new VisualState { Name = VisualStateManager.CommonStates.Normal }); + commonStates.States.Add(selected); + VisualStateManager.SetVisualStateGroups(label, new VisualStateGroupList { commonStates }); + } + + return label; + }), + ItemsSource = items + }; + var handler = CreateHandler(collectionView); + var recyclerView = handler.PlatformView; + int itemSize = (int)recyclerView.Context.ToPixels(40); + + // Five rows fit, so scrolling binds recycled rows to other items. + recyclerView.Measure( + AView.MeasureSpec.MakeMeasureSpec(4 * itemSize, global::Android.Views.MeasureSpecMode.Exactly), + AView.MeasureSpec.MakeMeasureSpec(5 * itemSize, global::Android.Views.MeasureSpecMode.Exactly)); + recyclerView.Layout(0, 0, 4 * itemSize, 5 * itemSize); + + var rowsBound = new HashSet(); + + void AssertSelection(params string[] selectedItems) + { + Assert.True(recyclerView.ChildCount > 0); + + for (int i = 0; i < recyclerView.ChildCount; i++) + { + var holder = (TemplatedItemViewHolder)recyclerView.GetChildViewHolder(recyclerView.GetChildAt(i)); + rowsBound.Add(holder); + var item = items[holder.BindingAdapterPosition]; + bool isSelected = selectedItems.Contains(item); + + Assert.True(isSelected == holder.IsSelected, $"{item}: IsSelected should be {isSelected}"); + Assert.True(isSelected == holder.ItemView.Activated, $"{item}: Activated should be {isSelected}"); + Assert.True(isSelected == holder.ItemView.Selected, $"{item}: Selected should be {isSelected}"); + Assert.True(isSelected == holder.View.IsItemSelected, $"{item}: IsItemSelected should be {isSelected}"); + + // The item view shows the default selection color, unless the template's visual states color the selection. + bool showsDefaultColor = isSelected && !templateColorsSelection; + Assert.True(showsDefaultColor == holder.ItemView.Background is not null, $"{item}: default selection color should be shown: {showsDefaultColor}"); + + if (templateColorsSelection) + { + var state = VisualStateManager.GetVisualStateGroups(holder.View)[0].CurrentState; + Assert.Equal(isSelected ? VisualStateManager.CommonStates.Selected : VisualStateManager.CommonStates.Normal, state?.Name); + } + } + } + + void ScrollRows(int rows, params string[] selectedItems) + { + // Three rows at a time: rows that leave the view are recycled and bound to the items that come into it. + for (int scrolled = 0; scrolled < System.Math.Abs(rows); scrolled += 3) + { + recyclerView.ScrollBy(0, System.Math.Sign(rows) * 3 * itemSize); + AssertSelection(selectedItems); + } + } + + AssertSelection(); + + if (selectionMode == SelectionMode.Single) + { + collectionView.SelectedItem = items[1]; + AssertSelection(items[1]); + + // Rows that were bound to the selected item are bound to unselected ones, and the other way round. + ScrollRows(30, items[1]); + ScrollRows(-30, items[1]); + + // The selection changes while the selected item is out of view. + ScrollRows(30, items[1]); + collectionView.SelectedItem = items[31]; + AssertSelection(items[31]); + ScrollRows(-30, items[31]); + ScrollRows(30, items[31]); + + collectionView.SelectedItem = null; + AssertSelection(); + ScrollRows(-30); + } + else + { + collectionView.SelectedItems = new List { items[1], items[3] }; + AssertSelection(items[1], items[3]); + + ScrollRows(30, items[1], items[3]); + collectionView.SelectedItems.Remove(items[1]); + collectionView.SelectedItems.Add(items[32]); + AssertSelection(items[3], items[32]); + ScrollRows(-30, items[3], items[32]); + ScrollRows(30, items[3], items[32]); + + collectionView.SelectedItems.Clear(); + AssertSelection(); + ScrollRows(-30); + } + + // Turning selection off clears the selection of the rows in view, and recycled rows stay unselected. + if (selectionMode == SelectionMode.Single) + { + collectionView.SelectedItem = items[1]; + } + else + { + collectionView.SelectedItems.Add(items[1]); + } + + AssertSelection(items[1]); + collectionView.SelectionMode = SelectionMode.None; + AssertSelection(); + ScrollRows(30); + ScrollRows(-30); + + // Far fewer rows were created than items were shown, so the checks covered recycled rows. + Assert.True(rowsBound.Count < 30, $"Expected recycled rows, but {rowsBound.Count} rows were created"); + }); + } + + [Theory(DisplayName = "CollectionView linear item spacing changes between zero and non-zero")] + [InlineData(ItemsLayoutOrientation.Vertical)] + [InlineData(ItemsLayoutOrientation.Horizontal)] + public async Task LinearItemSpacingChangesBetweenZeroAndNonZero(ItemsLayoutOrientation orientation) + { + SetupBuilder(); + + await InvokeOnMainThreadAsync(() => + { + var layout = new LinearItemsLayout(orientation); + var collectionView = new CollectionView + { + ItemsLayout = layout, + ItemTemplate = new DataTemplate(() => new Grid + { + WidthRequest = 40, + HeightRequest = 40 + }), + ItemsSource = new[] { "First", "Second", "Third" } + }; + var handler = CreateHandler(collectionView); + var recyclerView = handler.PlatformView; + + int itemSize = (int)recyclerView.Context.ToPixels(40); + int viewportSize = 8 * itemSize; + void MeasureAndLayout() + { + int spec = AView.MeasureSpec.MakeMeasureSpec(viewportSize, global::Android.Views.MeasureSpecMode.Exactly); + recyclerView.Measure(spec, spec); + recyclerView.Layout(0, 0, viewportSize, viewportSize); + } + + void AssertItems(int spacing) + { + for (int position = 0; position < 3; position++) + { + var holder = recyclerView.FindViewHolderForAdapterPosition(position); + Assert.NotNull(holder); + var child = holder.ItemView; + int start = position * (itemSize + spacing); + + Assert.Equal(start, orientation == ItemsLayoutOrientation.Vertical ? child.Top : child.Left); + Assert.Equal(start + itemSize, orientation == ItemsLayoutOrientation.Vertical ? child.Bottom : child.Right); + } + } + + // Without spacing, there is no decoration whose offsets RecyclerView would ask for every item. + MeasureAndLayout(); + Assert.Equal(0, recyclerView.ItemDecorationCount); + AssertItems(0); + + double requestedSpacing = recyclerView.Context.FromPixels(40); + // Android truncates each half-gap separately. + int expectedSpacing = 2 * (int)recyclerView.Context.ToPixels(requestedSpacing / 2); + Assert.True(expectedSpacing > 0); + + layout.ItemSpacing = requestedSpacing; + MeasureAndLayout(); + Assert.Equal(1, recyclerView.ItemDecorationCount); + AssertItems(expectedSpacing); + + layout.ItemSpacing = 0; + MeasureAndLayout(); + Assert.Equal(0, recyclerView.ItemDecorationCount); + AssertItems(0); + + layout.ItemSpacing = requestedSpacing; + MeasureAndLayout(); + Assert.Equal(1, recyclerView.ItemDecorationCount); + AssertItems(expectedSpacing); + }); + } + [Theory] [MemberData(nameof(SafeAreaItemViewTypes))] public async Task RecyclerItemWithoutExplicitSafeAreaEdgesDoesNotUseInsetListener(System.Type itemViewType)