Repository navigation
[Android] CollectionView: stop reapplying unchanged selection and drop the zero-spacing item decoration - #40901
Conversation
…ry bind SelectableItemsViewAdapter sets SelectableViewHolder.IsSelected for every item it binds and every item it recycles, and the setter applied the value every time: it set the item view's Foreground, Background, Activated and Selected (four calls into Java), scanned the content's visual state groups and set IsItemSelected. With SelectionMode None the value is always false, so a scrolling list did this twice per row for nothing. Binding and recycling now go through UpdateIsSelected, which skips a value that the item view and its content already show. A holder still applies its selection the first time, and again after TemplatedItemViewHolder replaces its content, whose IsItemSelected starts out false and whose visual states decide whether the default selection color applies. Selection changes (MarkPlatformSelection, ClearPlatformSelection and clicks) set IsSelected as before. The new device test checks that rows recycled while scrolling show the selection of the item they are bound to, for Single and Multiple selection, with the default selection color and with a Selected visual state, also when the selection changes while the selected item is out of view, and after selection is turned off. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
UpdateItemSpacing always added a SpacingItemDecoration, also when the spacing is zero, as it is by default. Its GetItemOffsets then returns without offsetting anything, but RecyclerView still calls it from Java for every item it binds and lays out: a call into .NET per row, which looks up the peers of its four arguments and calls back into Java for base.GetItemOffsets. Without spacing, no decoration is added now; the RecyclerView's padding is still reset. Changing the spacing to or from zero removes or adds the decoration. A decoration from an overridden CreateSpacingDecoration, including a subclass of SpacingItemDecoration, is always added. The device tests check the decoration count and the items' bounds as the spacing changes from zero to non-zero and back, for linear layouts in both orientations and, extending the existing test, for grids. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
|
/review expert-review |
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
🟡 Changes recommended
A selected-holder rebind can lose its highlight after a style change, and the recycling test can pass without proving that holders were reused or scrolling reached the intended range.
2 open issues
What changed in this PR
This PR reduces redundant Android CollectionView work during scrolling by skipping repeated selection updates and omitting the built-in spacing decoration when its offsets are zero.
Changes:
- Adds cached selection application for binding and recycling, invalidated when template content changes.
- Removes zero-offset built-in spacing decorations while preserving custom decoration subclasses.
- Adds Android device tests for recycled-row selection and zero/non-zero spacing transitions.
| File | Description |
|---|---|
src/Controls/tests/DeviceTests/Elements/CollectionView/CollectionViewTests.Android.cs |
Adds selection recycling and spacing-transition coverage. |
src/Controls/src/Core/Handlers/Items/Android/TemplatedItemViewHolder.cs |
Invalidates cached selection when content is replaced. |
src/Controls/src/Core/Handlers/Items/Android/SelectableViewHolder.cs |
Adds the unchanged-selection fast path. |
src/Controls/src/Core/Handlers/Items/Android/MauiRecyclerView.cs |
Omits the built-in decoration when spacing offsets are zero. |
src/Controls/src/Core/Handlers/Items/Android/Adapters/SelectableItemsViewAdapter.cs |
Uses cached selection updates during binding and recycling. |
Review effort: Balanced
| /// </remarks> | ||
| internal void UpdateIsSelected(bool isSelected) | ||
| { | ||
| if (_isSelectionApplied && _isSelected == isSelected) |
| // 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"); |
There was a problem hiding this comment.
Expert Review — 1 finding
Reviewed commit 949b79d.
Source assessment incomplete (10/11 dimensions); finding count is partial.
See inline comments for details.
| // 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)) |
There was a problem hiding this comment.
[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.
Selected Tests
🧪 Test selection — click to expand
🧪 UI tests —
|
| Platform | Categories |
|---|---|
| Android | CarouselView, CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7 |
🧪 Device tests — Controls.CarouselView, Controls.CollectionView on Android
❌ Could not queue maui-pr-devicetests: Azure Pipelines did not start maui-pr-devicetests for the dispatch branch run-devicetests/pr40901-46504503874 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-devicetests for the full suite.
GPT-6.2 Sol: Run Android Controls device tests for CollectionView selection and spacing and CarouselView decoration regressions.
MAI Code 2: Android CollectionView handler and device tests; run Controls CollectionView and CarouselView units on Android.
🧪 Running — 2 categories on Android
| Platform | Categories |
|---|---|
| Android | Controls.CarouselView, Controls.CollectionView |
⏭️ Skipped — what neither suite runs
UI tests — 69 categories, 3 platforms
Platforms not run: iOS, MacCatalyst, Windows
Categories not run: Accessibility, ActionSheet, ActivityIndicator, Animation, AppLinks, Border, BoxView, Brush, Button, Cells, CheckBox, ContextActions, CustomRenderers, DatePicker, Dispatcher, DisplayAlert, DisplayPrompt, DragAndDrop, Entry, Editor, Effects, Essentials, FlyoutPage, Focus, Fonts, Frame, Gestures, GraphicsView, Image, ImageButton, IndicatorView, InputTransparent, IsEnabled, IsVisible, Label, Layout, Lifecycle, ManualReview, Maps, Navigation, Page, Performance, Picker, ProgressBar, RadioButton, RefreshView, SafeAreaEdges, Shadow, ScrollView, SearchBar, Shape, Slider, SoftInput, Stepper, Switch, SwipeView, Shell1, Shell2, TabbedPage, TableView, TimePicker, TitleView, ToolbarItem, Triggers, ViewBaseTests, VisualStateManager, Window, WebView, Material3
Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.
Device tests — 103 categories, 3 platforms
Platforms not run: iOS, MacCatalyst, Windows
Categories not run: Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CheckBox, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.Memory, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay, Graphics, Essentials, BlazorWebView
Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.
🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)
UI tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, CarouselView |
CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, CarouselView |
| iOS | — | — |
| MacCatalyst | — | — |
| Windows | — | — |
GPT-6.2 Sol — Run Android CollectionView and CarouselView UI tests for recycled selection and shared RecyclerView spacing changes.
- Adapter and holder changes affect CollectionView selection visuals during recycling.
- MauiRecyclerView changes decoration replacement shared with CarouselView.
- No other platforms or Material3 rendering paths changed.
MAI Code 2 — Android-only CollectionView item selection and spacing changes; run CollectionView and CarouselView UI coverage on Android.
SelectableItemsViewAdapter,SelectableViewHolder, andTemplatedItemViewHolderchange Android item selection application used by the Items handler stack.MauiRecyclerViewchanges Android item-decoration creation and zero-spacing behavior for collection-style controls.- Run CollectionView for direct coverage and CarouselView because it shares the Items handler path; leave other platforms out because all changed production and test files are Android-specific.
Device tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | Controls.CollectionView, Controls.CarouselView |
Controls.CollectionView, Controls.CarouselView |
| iOS | — | — |
| MacCatalyst | — | — |
| Windows | — | — |
GPT-6.2 Sol — Run Android Controls device tests for CollectionView selection and spacing and CarouselView decoration regressions.
- CollectionViewTests.Android.cs adds recycled selection and zero/nonzero grid and linear spacing coverage.
- CarouselView exercises the shared MauiRecyclerView decoration lifecycle.
- No Core handler or non-Android code changed.
MAI Code 2 — Android CollectionView handler and device tests; run Controls CollectionView and CarouselView units on Android.
- The changed Controls Items handlers affect Android CollectionView selection binding, recycling, and spacing decorations.
- The modified Android device tests directly cover zero/non-zero spacing and recycled-row selection states.
- Include CarouselView because it shares the Items handler stack; exclude other platforms and unrelated control categories.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.

Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
949b79d0638d22483c94bae3f804090cd6646aca↑ New device tests cover the selection of recycled rows (Single and Multiple, default color and Selected visual state) and spacing changes between zero and non-zero (linear in both orientations, grid).
↑ A trace shows the removed work gone (selection 2.2% and GetItemOffsets 0.8% of UI-thread samples, both to 0), with allocations unchanged.
↓ No speed-up is measurable on the emulator, and the A/B included a third commit that is no longer part of this PR.
↓ Android UI tests, CI and physical devices not run yet.
↓ OnSelectedChanged is no longer called on bind or recycle when the selection doesn't change, which a custom SelectableViewHolder subclass could notice.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for reviewThis is .NET 12 performance work, so it targets
main.For .NET 11 fixes, only a maintainer retargets the approved PR to the active
inflight lane and merges it after CI validates that final base. Do not merge
individual fixes directly into
net11; agents must not retarget or merge.Description of Change
When a CollectionView scrolls on Android, every row that comes into view is bound and every row that leaves it is recycled. Two parts of that work called into Java (or were called from Java) for every row without changing anything. This PR removes those calls. What the user sees doesn't change.
1. Don't reapply an unchanged selection
Files:
SelectableViewHolder.cs,SelectableItemsViewAdapter.cs,TemplatedItemViewHolder.csSelectableItemsViewAdaptersetsSelectableViewHolder.IsSelectedfor every item it binds and every holder it recycles. The setter always applied the value:Foreground,Background,ActivatedandSelected. Each of these is a JNI call after a JNI read ofViewHolder.ItemView.IsItemSelected.With
SelectionMode.Nonethe value is alwaysfalse. So for every row it scrolled, a list made 8 JNI field reads (with peer lookups) and 8 JNI property sets that changed nothing.Binding and recycling now call a new internal
UpdateIsSelected, which skips a value that the item view and its content already show.TemplatedItemViewHolderreplaces its content: new content isn't selected yet, and its visual states decide whether the default selection color applies.IsSelectedas before:MarkPlatformSelection,ClearPlatformSelectionand clicks, including the unconditional re-sync from [Android] CollectionView: Fix SelectedItem visual state not applying when re-selecting same item #31591. The publicIsSelectedsetter is unchanged.2. No item decoration without item spacing
File:
MauiRecyclerView.cs(UpdateItemSpacing)UpdateItemSpacingalways added aSpacingItemDecoration, even when the spacing is zero, which is the default. ItsGetItemOffsetsthen offsets nothing. RecyclerView still calls it from Java for every row it binds, and each call looks up the peers of its four arguments and calls back into Java forbase.GetItemOffsets.Now no decoration is added without spacing; the RecyclerView's padding is still reset as before.
CreateSpacingDecorationis always added, including a subclass ofSpacingItemDecoration.Why it's safe
_currentViewHolders, so selection changes still reach them.willNotDrawstaysfalse, because CollectionView doesn't setOverScrollMode.Never.InvalidateItemDecorations()becomes a no-op when there's nothing to invalidate.Behavior changes
SelectableViewHolder.OnSelectedChanged()(protected virtual) is no longer called when binding or recycling a holder doesn't change its selection. A custom subclass that used it as a per-bind hook would see fewer calls.MauiRecyclerView.ItemDecorationCountis 0 instead of 1.Results
The numbers come from the CollectionView scroll benchmark (source, pushed for reference; it isn't part of this or any PR).
SelectionMode.Noneand zero spacing.Setup:
Allocations are unchanged: 20,009 B/row in both (difference 0 [0 .. 0]), with 2 gen0 GCs per pass.
Timing: no significant difference. The emulator resolves only differences of about 20% or more.
In run 1, the candidate's slow passes also took more UI-thread CPU for the same rows. That points to the emulator losing CPU to the host rather than to the change, and runs 2 and 3 didn't reproduce it. Run 3's control shows the same small lean between two builds of the same commit.
Trace evidence for the two changes in this PR. I traced the candidate with the EventPipe sample profiler over 8 warm passes (2,136 rows) and compared it with a trace of main. The traces were taken at different times, so compare shares, not totals.
SelectableViewHolderframes (SetSelectionStates, theIsSelectedsetter)ViewHolder.ItemView(GetObjectField)SpacingItemDecoration.GetItemOffsets, called from JavaPer bound row, the two changes remove:
Tests
New device tests in
CollectionViewTests.Android.cs:RecycledItemsShowTheirOwnSelection(4 cases). Single and Multiple selection, each with the default selection color and with a template that colors selection through aSelectedvisual state. It scrolls so that rows are recycled, changes the selection while the selected item is out of view, and turns selection off. Every row in view must show the selection of the item it is bound to:IsSelected,Activated,Selected,IsItemSelected, the default color and the visual state.LinearItemSpacingChangesBetweenZeroAndNonZero(vertical, horizontal). It checks the decoration count and item bounds as the spacing goes 0 → 40 px → 0 → 40 px.GridItemOffsetsExcludeCrossAxisOuterSpacing(existing, 4 cases) now also checks the decoration count and the non-zero → zero transition.Run on this revision, on an Android 15 (API 35) emulator, Release:
Result: Passed. 315 total, 314 passed, 1 skipped (
CellSizeAccountsForMargin, skipped by its attribute), 0 failed.dotnet format whitespace --folder --verify-no-changeson the changed files reports nothing new.SelectableItemsViewAdapter.cshas 27 whitespace issues that are also on main; I left them, because #40881 reformats that file.Not run:
Overlap with #40881
#40881 also edits
SelectableItemsViewAdapter.cs. Merging the two conflicts inOnViewRecycled, where each PR changes one of two adjacent lines. The bind path merges cleanly. The resolution keeps both:Issues Fixed
None; this was found by profiling.
Related:
SelectableItemsViewAdapter.cs; see above.Let AI finish this PR