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
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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);
Expand Down
18 changes: 15 additions & 3 deletions src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[moderate] Regression Prevention and Test Coverage - The spacing tests only use the base decoration, leaving the exact-type exclusion untested. Removing the GetType condition would satisfy every added spacing assertion while disposing and omitting a derived SpacingItemDecoration whose base offsets are zero but whose GetItemOffsets supplies custom insets. Add a fixture overriding CreateSpacingDecoration with that subclass and assert that it remains installed and its custom offsets affect item bounds.

{
spacingDecoration.Dispose();
return;
}
}

_itemDecoration = itemDecoration;
AddItemDecoration(_itemDecoration);
}

protected virtual ItemDecoration CreateSpacingDecoration(IItemsLayout itemsLayout)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -46,6 +48,7 @@ public bool IsSelected
set
{
_isSelected = value;
_isSelectionApplied = true;

SetSelectionStates(_isSelected);

Expand All @@ -55,6 +58,28 @@ public bool IsSelected
}
}

/// <summary>
/// Sets <see cref="IsSelected"/>, unless the item view and its content already show <paramref name="isSelected"/>.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal void UpdateIsSelected(bool isSelected)
{
if (_isSelectionApplied && _isSelected == isSelected)
{
return;
}

IsSelected = isSelected;
}

/// <summary>
/// Makes the next <see cref="UpdateIsSelected"/> apply the selection, because the item's content has been replaced.
/// </summary>
internal void InvalidateIsSelected() => _isSelectionApplied = false;

protected virtual bool UseDefaultSelectionColor => true;

public void OnClick(global::Android.Views.View view)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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)
{
Expand All @@ -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);
});
}

Expand Down Expand Up @@ -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<CollectionViewHandler>(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<global::AndroidX.RecyclerView.Widget.RecyclerView.ViewHolder>();

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<object> { 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");
Comment on lines +918 to +919
});
}

[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<CollectionViewHandler>(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)
Expand Down
Loading