Skip to content

[Android] CollectionView: stop reapplying unchanged selection and drop the zero-spacing item decoration - #40901

Merged
kubaflo merged 2 commits into
mainfrom
simonrozsival-android-collectionview-bind-fixes
Nov 30, 2026
Merged

kubaflo merged 2 commits into
mainfrom
simonrozsival-android-collectionview-bind-fixes

Conversation

@simonrozsival

Copy link
Copy Markdown
Member

Agent assessment

Self-reported assessment, not an independent review.

Assessed revision: 949b79d0638d22483c94bae3f804090cd6646aca

Dimension Assessment Rationale
Change confidence 8.5/10 ↑ Android CollectionViewTests and CarouselViewTests pass on this revision: 314 passed, 1 skipped by its attribute, 0 failed (Android 15 emulator).
↑ 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

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

This 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.cs

SelectableItemsViewAdapter sets SelectableViewHolder.IsSelected for every item it binds and every holder it recycles. The setter always applied the value:

  • It set the item view's Foreground, Background, Activated and Selected. Each of these is a JNI call after a JNI read of ViewHolder.ItemView.
  • It scanned the content's visual state groups and set IsItemSelected.

With SelectionMode.None the value is always false. 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.

  • A holder applies its selection the first time it is bound.
  • It applies it again after TemplatedItemViewHolder replaces its content: new content isn't selected yet, and its visual states decide whether the default selection color applies.
  • Selection changes still set IsSelected as before: MarkPlatformSelection, ClearPlatformSelection and clicks, including the unconditional re-sync from [Android] CollectionView: Fix SelectedItem visual state not applying when re-selecting same item #31591. The public IsSelected setter is unchanged.

2. No item decoration without item spacing

File: MauiRecyclerView.cs (UpdateItemSpacing)

UpdateItemSpacing always added a SpacingItemDecoration, even when the spacing is zero, which is the default. Its GetItemOffsets then 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 for base.GetItemOffsets.

Now no decoration is added without spacing; the RecyclerView's padding is still reset as before.

  • Changing the spacing to or from zero removes or adds the decoration.
  • A decoration from an overridden CreateSpacingDecoration is always added, including a subclass of SpacingItemDecoration.
  • CarouselView uses its own decoration and is not affected.

Why it's safe

  • Selection: the check only skips writing values that are already applied. It is reset whenever a holder's content is replaced. Holders that RecyclerView keeps in its view cache stay in _currentViewHolders, so selection changes still reach them.
  • Decoration:
    • A decoration whose offsets are all zero has the same effect as no decoration.
    • RecyclerView's willNotDraw stays false, because CollectionView doesn't set OverScrollMode.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.
  • Selection visuals are reapplied only when the selection changes or the holder's content is replaced, not at every bind.
  • With zero spacing, MauiRecyclerView.ItemDecorationCount is 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).

  • What it scrolls: a CollectionView of 1,000 items. Each row is a Grid with a BoxView, 7 Labels, a ProgressBar and a CheckBox, with 13 compiled bindings and the default SelectionMode.None and zero spacing.
  • How it scrolls: 100 dp per frame for 240 frames per pass, which binds about 267 rows per pass.
  • Method: base and candidate launches are interleaved. Each launch is reduced to the median of its 5 warm passes, launches are paired by round, and the result is the median paired difference with a 95% sign-test interval.

Setup:

  • Base is main bd40bc6.
  • The candidate is this PR plus a third commit that coalesced layout requests during a rebind. I dropped that commit from this PR because it added machinery to Core without a measurable gain. So the A/B measured all three changes together.
  • Device: an Android 15 emulator (Pixel 6 profile, android-35 google_apis arm64-v8a, 4 cores, 4 GB) on a shared, heavily loaded Mac (load average 15–64).
  • Runtime: CoreCLR .NET 12.0.0-alpha.1.26523.103, Release builds.

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.

Run (rounds) Rebind, UI-thread CPU per row UI-thread CPU per row Wall time per pass
1, vs main build (12) +5.5% [−24.1 .. 56.1 µs] +7.5% [−70 .. 390 µs] +20.6% [34 .. 2,584 ms] *
2, vs main build, reversed order (12) +6.6% [−17.0 .. 28.8 µs] +8.8% [−116 .. 170 µs] +0.7% [−81 .. 211 ms]
3, vs main built in the same checkout (10) +1.5% [−15.9 .. 10.6 µs] −2.6% [−88.6 .. 60.8 µs] 0.0% [−86 .. 3 ms]
3, control: main vs main, two builds (10) +2.8% [−3.1 .. 15.6 µs] +2.6% [−22.0 .. 139.8 µs] +0.1% [−1 .. 85 ms]

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.

UI-thread samples main candidate
Total 1,434 1,095
SelectableViewHolder frames (SetSelectionStates, the IsSelected setter) 32 (2.2%) 0
… of which JNI reads of ViewHolder.ItemView (GetObjectField) 18 (1.3%) 0
SpacingItemDecoration.GetItemOffsets, called from Java 11 (0.8%) 0

Per bound row, the two changes remove:

  • 8 JNI property sets and 8 JNI field reads, when the selection doesn't change;
  • 1 call from Java into .NET with 4 peer lookups, plus 1 call back into Java, when there's no spacing.

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 a Selected visual 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:

pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -DeviceUdid emulator-5620 -DotnetPath $PWD/.dotnet/dotnet -IncludeClasses 'Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.CarouselViewTests' -Timeout 01:30:00

Result: Passed. 315 total, 314 passed, 1 skipped (CellSizeAccountsForMargin, skipped by its attribute), 0 failed.

dotnet format whitespace --folder --verify-no-changes on the changed files reports nothing new. SelectableItemsViewAdapter.cs has 27 whitespace issues that are also on main; I left them, because #40881 reformats that file.

Not run:

  • Android UI tests (Appium), including the selection screenshot tests; left to CI.
  • Physical devices.
  • iOS, Mac Catalyst and Windows, which these Android-only files don't affect.
  • Unit tests, since no shared code changed.

Overlap with #40881

#40881 also edits SelectableItemsViewAdapter.cs. Merging the two conflicts in OnViewRecycled, where each PR changes one of two adjacent lines. The bind path merges cleanly. The resolution keeps both:

selectable.Clicked -= SelectableClickedHandler;
selectable.UpdateIsSelected(false);

Issues Fixed

None; this was found by profiling.

Related:

Let AI finish this PR

  • Let the MAUI agent address review feedback and fix remaining issues on this PR. Maintainers still decide whether it is merged. For PRs from forks, keep "Allow edits by maintainers" on so the agent can push to your branch; otherwise it opens a follow-up PR that keeps your commits.

simonrozsival and others added 2 commits November 30, 2026 17:30
…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>
Copilot AI balanced review requested due to automatic review settings November 30, 2026 20:01
@github-actions

This comment has been minimized.

@kubaflo

kubaflo commented Nov 30, 2026

Copy link
Copy Markdown
Contributor

/review expert-review

@github-actions github-actions Bot added area-controls-collectionview CollectionView, CarouselView, IndicatorView platform/android labels Nov 30, 2026
@kubaflo

This comment has been minimized.

Copilot AI left a comment

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.

🟡 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)
Comment on lines +918 to +919
// 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");

@github-actions github-actions Bot left a comment

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.

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))

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.

@github-actions

Copy link
Copy Markdown
Contributor

Selected Tests

@kubaflo — AI-selected UI tests and device tests (GPT-6.2 Sol + MAI Code 2) for commit 949b79d0.

Result NOT QUEUED Platforms Android Tests 8 UI, 2 device Commit 949b79d0


🧪 Test selection — click to expand
Suite Result Selected Build
UI tests ❌ not queued 8 of 77 categories —
Device tests ❌ not queued 2 of 105 units —
🧪 UI tests — CarouselView, CollectionView1, CollectionView2, CollectionView3 +4 on Android

❌ Could not queue maui-pr-uitests: Azure Pipelines did not start maui-pr-uitests for the dispatch branch run-tests/pr40901-46504503874 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-uitests for the full suite.

GPT-6.2 Sol: Run Android CollectionView and CarouselView UI tests for recycled selection and shared RecyclerView spacing changes.
MAI Code 2: Android-only CollectionView item selection and spacing changes; run CollectionView and CarouselView UI coverage on Android.

🧪 Running — 8 categories on Android

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, and TemplatedItemViewHolder change Android item selection application used by the Items handler stack.
  • MauiRecyclerView changes 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.

@kubaflo
kubaflo merged commit 62836b0 into main Nov 30, 2026
15 of 18 checks passed
@kubaflo
kubaflo deleted the simonrozsival-android-collectionview-bind-fixes branch November 30, 2026 21:47

This branch was previously deployed

1 inactive deployment
copilot-pat-pool — 949b79d0 Deployed Nov 30, 2026 by simonrozsival via conclusion #3549
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-controls-collectionview CollectionView, CarouselView, IndicatorView platform/android

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants