Repository navigation
[Android] Fix CollectionView ItemSpacing when items are added or removed at runtime - #40318
Conversation
… content (dotnet#40169) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [ ] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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. ### Issue Description On Android 16, switching between Entries with different keyboard types can briefly display the previous keyboard layout before showing the correct one, causing visible flickering. In the reproduction, each Entry is dynamically added to a ContentView and replaced with a Label when another cell is selected. ### Root Cause RemoveAllViews() detached the focused native EditText without explicitly clearing its focus. Removing a view is not the same as completing a focus transition. Android updates the keyboard through its input-method system asynchronously. If the outgoing text field is still considered the active input target, the keyboard can temporarily retain its configuration while Android processes detachment, transfers focus, and establishes the incoming Entry’s input connection. ### Description of Change - Clear native focus from the outgoing ContentView content before calling RemoveAllViews() on Android. - Previously, removing content containing a focused Entry could leave stale input-method state. When switching between Entries with different keyboard types, the previous keyboard layout could briefly appear before the correct layout. - Explicitly clearing focus before removing the native view ensures that the outgoing Entry relinquishes focus before the next Entry is attached and focused. ### Issues Fixed Fixes dotnet#38799 ### Tested the behaviour in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Output Screenshot Before Issue Fix | After Issue Fix | |----------|----------| |<video width="300" height="600" alt="Before Fix" src="https://github.com/user-attachments/assets/62b49b56-86e3-48e8-9ae1-19e92106f5b0">|<video width="100" height="100" alt="After Fix" src="https://github.com/user-attachments/assets/55caabe9-2021-43c0-9407-31bbad08db4c">| Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…et#40175) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [ ] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 This pull request primarily improves shadow rendering support for Win2D-based shapes on Windows and updates test conditions related to shadow features. The most significant changes are the addition of logic to handle `W2DGraphicsView` with `ShapeDrawable` in shadow rendering, as well as updates to test preprocessor directives and references. **Shadow rendering improvements:** * [`ShadowExtensions.cs`](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R43-R51): Added logic in `GetAlphaMaskAsync` to handle `W2DGraphicsView` with `ShapeDrawable`, using the live visual for shadow rendering since `RenderTargetBitmap` cannot capture Win2D content. * [`ShadowExtensions.cs`](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R7): Added necessary using directives for `Microsoft.Maui.Graphics.Win2D` and aliased `ShapeDrawable` for clarity. [[1]](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R7) [[2]](diffhunk://#diff-6c904999b229ffd792f069a6a0ddaf850a67a046624c4e915b57ece230ca9a09R16) **Test updates:** * [`ShadowFeatureTests.cs`](diffhunk://#diff-560f9cb1cec21af3a1c6ae51a0b30849aea0f019d519990a0b24dba91971d67fL218-R218): Updated the Windows shadow test exclusion to reference the correct GitHub issue (`40172` instead of `27732`). * [`BoxViewFeatureTests.cs`](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L163): Removed the preprocessor directive that disabled shadow tests on Windows, re-enabling those tests. [[1]](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L163) [[2]](diffhunk://#diff-3455b54055dcfe7c51234f9e7cc13af77da827ea7b097f7fe77d44acad4b0f79L235) <!-- Enter description of the fix in this section --> ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> Fixes dotnet#31821 ### Tested the behavior in the following platforms - [x] Windows - [ ] Android - [ ] iOS - [ ] Mac | Before Issue Fix | After Issue Fix | |----------|----------| | <img width="998" height="944" alt="BeforeFix1821" src="https://github.com/user-attachments/assets/b4a526d3-a615-4fea-9ede-55129e23314e" /> | <img width="1259" height="952" alt="AfterFix31821" src="https://github.com/user-attachments/assets/17282ba8-85cb-48a0-814b-beac7642c7b6" /> | <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
) <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Most of the recent `net11` `maui-pr-uitests` red comes from Android API 30 jobs that are cancelled at the 240-minute job limit. The cause is a lost emulator, not product regressions. **What happens** (raw logs of build [1680926](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1680926) and [1680462](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1680462), e.g. API 30 Navigation and API 30 CollectionView3): 1. The emulator boots normally, and tests run for about 9–12 minutes. 2. `[Logcat] Logcat terminated with code 255` appears and adb reports `device 'emulator-5554' not found`. The emulator is gone. 3. The remaining fixtures of attempt 1 fail quickly once session recreation fails. 4. `RunUITestsWithRetry` starts **UI test attempt 2** against the still-missing device. Every fixture now waits about 3.7 minutes in `AppiumServerContext.CreateUIClientContext`: 11 tries × Appium's 20-second "Could not find a connected Android device". 5. The job runs until Azure DevOps cancels it at 240 minutes. Most of the failed rows in those builds are these setup failures. The same tests pass on `candidate/11.0.1xx-sr2`, and none of `eng/devices`, `UITest.Appium` or `UITest.NUnit` differs between `net11`, the candidate and `main`. So this is an infrastructure flake that the retry path amplifies, with no existing fix to backport. **Fix** - `RunUITestsWithRetry` gets an optional `beforeAttempt` hook that runs before **every** attempt, including attempt 1. The iOS, Mac Catalyst and Windows callers are unchanged. - Running it only before retries was not enough. In this PR's run [1682445](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682445), three API 30 jobs installed the app and then lost the emulator during the roughly 2-minute UI-test project build, before attempt 1. Every fixture in attempt 1 then waited 3 min 40 s (Shell1: 68 fixtures, CarouselView: 99, 0 passed), and the jobs were cancelled at 240 minutes before the retry hook could run. - On Android, the hook checks `sys.boot_completed`: - If the device is healthy, it does nothing (one `getprop`). - If the emulator started by the script is gone, it cleans up, restarts the emulator through the existing `HandleVirtualDevice` path, and reinstalls the app with `ExecutePrepareUITests` before the attempt. - If that cleanup throws (for example `AdbEmuKill` fails), the hook kills the old emulator process directly before restarting, so the same AVD is never started twice. In a local fault-injection check, the previous code left the old PID alive, started a duplicate, and timed out after about 10 minutes; with this fallback, recovery finished in 39 s. - Before restarting, the hook waits (bounded by `EmulatorKillTimeoutSeconds`) until the old process has **confirmed exited**. If it hasn't, the hook fails the attempt rather than start a duplicate instance of the same AVD. - If the device was not started by the script, it logs a warning and runs the tests as before. Local runs against a user-supplied device are unchanged. - `uitest-retry.cake`: a retry no longer leaves never-run ignored tests as failures. When the device is lost during a fixture's OneTimeSetUp, NUnit fails every child with `site="Parent"`. If OneTimeTearDown also throws, the fixture site becomes `TearDown` instead of `SetUp`. Ignored tests then come back from a green retry as Skipped/Ignored: either a static `[Ignore]` with the same reason, or a runtime `Assert.Ignore` with `runstate="Runnable"`. The merge accepted only the `SetUp`+static-reason shape, so the job failed even though the retry was green. - The merge now treats a parent-site error as never-run when the fixture failed in setup (site `SetUp`, or the child's message starts with `OneTimeSetUp:`). It accepts a retry that ignores such a test, and accepts fixtures that contain only such recovered ignores. A test that actually ran and failed is still never accepted. **Validation** - `dotnet cake eng/devices/{android,catalyst,windows,ios}.cake --target=uitest --dryrun` compiles. iOS has the same pre-existing local teardown error with and without this change. - Local end-to-end check on an API 30 arm64 emulator (adb pinned to `emulator-5554`): a temporary target ran the real `connectToDevice` and `uitest-prepare` (installed the app), then called `EnsureDeviceForUITestAttempt` as at the attempt-1 call site. | Case | Result | | --- | --- | | Healthy device | Hook returned in 0.0 s (no-op) | | `adb emu kill` after install (the 1682445 mode) | `boot_completed` → null; hook logged the warning, restarted the emulator, and reinstalled the app (XHarness exit code 0) in 46 s; afterwards `boot_completed` = 1 and `pm path` showed the app | | Healthy again after recovery | 0.0 s no-op | | Missing device not started by the script | Warning logged, no throw | - Confirmed-exit fault injection (local, API 30): | Scenario | Before | After | | --- | --- | --- | | Cleanup returns but the emulator stays alive | Duplicate start; boot timed out after 10m32s | Attempt fails after 60 s with "did not exit … not restarting"; no duplicate | | Emulator killed externally | — | One restart, app reinstalled, XHarness exit 0 (49 s) | | Cleanup throws | — | Direct kill, one restart, XHarness exit 0 (41 s) | - **CI proof of recovery:** in this PR's run [1682664](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682664), Controls (API 30) Label lost the emulator during attempt 1. All 126 tests failed in OneTimeSetUp, about 3m40s each. Before attempt 2 the hook restarted Emulator_30 and reinstalled the app, and **attempt 2 passed 124 tests with 2 skipped** in 14 minutes. - **Retry merge:** that job was still marked failed because two never-run ignored tests stayed Failed: `Issue488TestsLongTextRotation` (static `[Ignore]`, fixture site `TearDown`) and `LabelUITests.IsEnabled` (runtime `Assert.Ignore`). The real TRX and NUnit XML from both attempts were replayed offline through `UITestRetry.MergeResults`: | Input | Before | After | | --- | --- | --- | | Real 1682664 Label artifacts | Merged outcome Failed (`IsEnabled`, `Issue488TestsLongTextRotation`) | Completed, 0 failed, no run errors | | Retry `IsEnabled` actually fails | — | Failed | | Original `IsEnabled` actually ran (site not Parent) | — | Failed | | Static ignore reason mismatch | — | Failed | | No `OneTimeSetUp:` evidence | — | Failed | The replay harness was local only; no test was committed, per policy for CI scripts. - Final validation is this PR's own `maui-pr-uitests` run. ### Issues Fixed Fixes Android API 30 `maui-pr-uitests` jobs on `net11` hanging until the 240-minute timeout after the emulator is lost mid-run. Also fixes recovered retries still failing the job when never-run ignored tests come back as Skipped/Ignored. --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
…dotnet#40300) <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Follow-up to dotnet#40273, which recovers a lost Android emulator **between** UI test attempts. That recovery cannot help when the emulator dies **during** an attempt: every remaining fixture then calls `AppiumServerContext.CreateUIClientContext`, which tries to create a session 11 times (`retries++ < 10`, about 20s each because UiAutomator2 waits 20s for a device). Each fixture fails only after **3m40s**. Evidence from `maui-pr-uitests` run [1682664](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1682664) (PR dotnet#40273), job "Controls (API 30) Label": - The emulator vanished about 3 minutes into attempt 1. - All 126 Label tests then failed in `OneTimeSetUp` with `Could not find a connected Android device in 20000ms`, each after 3m40s. - The test step took **195 minutes**; normally it takes 16–23 minutes. - Only after that did the between-attempt recovery restart the emulator. `net11` run [1683205](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1683205) showed the same job still running after 115+ minutes. The candidate (dotnet#40116) and `main` have identical copies of this file, so no existing fix covers it. **Change:** after one fixture exhausts all retries, later fixtures in the same test process get a single attempt. A successful session restores full retries. - The first failure still gets the full retry budget, so transient Appium or device hiccups keep the current tolerance. - CI retries start a new `dotnet test` process, so each attempt starts with full retries, and the emulator recovery from dotnet#40273 still runs before it. - No test is skipped, and no tolerance or baseline changes. ### Validation Ran a local console harness that references `UITest.Core` and `UITest.Appium`, starts the real Appium server (uiautomator2 3.9.1), and calls `CreateUIClientContext` with an Android config and no connected device. This simulates fixtures after the emulator is lost. | Build | Fixture 1 | Fixture 2 | Fixture 3 | | --- | --- | --- | --- | | `net11` (baseline, d0547a0) | 221s | 221s | — | | This PR | 221s | 20s | 20s | For a 126-fixture category, the time to fail after losing the emulator drops from about 7.7h (capped by the job timeout) to about 45 min. The same error message is still reported for every test. ### Issues Fixed Fixes CI hangs in `maui-pr-uitests` Android jobs after mid-attempt emulator loss (no tracking issue). Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
|
Azure Pipelines: There may be pipelines that require an authorized user to comment /azp run to run. |
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40318Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40318" |
|
Hey there @marcelomoresco! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
This comment has been minimized.
This comment has been minimized.
|
/rebase |
…ved at runtime Since dotnet#27093/dotnet#34664, SpacingItemDecoration leaves out the spacing on the outer edges, so an item's offsets depend on its position. RecyclerView only recomputes the offsets of items it rebinds or shifts, so after an append the previous last item kept a bottom offset of 0 (half spacing between items) and after removing the last item the new last item kept its bottom offset. MauiRecyclerView now invalidates the item decorations when the items adapter changes (only for a spacing decoration with a non-zero offset, and not while RecyclerView computes a layout). For grids, SpacingItemDecoration takes the span index from the SpanSizeLookup during pre-layout, where the LayoutParams still hold the span of the item's old position.
5b78c55 to
66fce23
Compare
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
| && (spacing.HorizontalOffset != 0 || spacing.VerticalOffset != 0) | ||
| && !IsComputingLayout) | ||
| { | ||
| InvalidateItemDecorations(); |
There was a problem hiding this comment.
[moderate] Performance-Critical Path Optimization - Content-only replacements now invalidate decorations across the viewport. For a spaced CollectionView receiving frequent off-screen replacements (items[index] = replacement), ObservableItemsSource.Replace sends a targeted NotifyItemChanged, but DataChangeObserver.OnItemRangeChanged also invokes this callback. InvalidateItemDecorations() dirties all attached decoration offsets and requests layout even though item positions, count and spacing are unchanged; previously RecyclerView could consume those off-screen updates without laying out the viewport. Preserve the notification kind/range so content-only updates do not trigger global spacing invalidation. The new tests cover only insertions/removals.
There was a problem hiding this comment.
Fixed in ccf4b52: the spacing observer now reacts only to structural changes (insert, remove, move, reset). Replacements keep every position and RecyclerView recomputes the offsets of the items it rebinds. Added a test that replaces an off-screen item and checks no other item offsets are recomputed (22 before, 0 after).
Replacing items (NotifyItemChanged/NotifyItemRangeChanged) keeps every position, and RecyclerView recomputes the offsets of the items it rebinds, so the spacing observer now ignores item changes instead of invalidating the decorations of the whole viewport. Inserts, removes, moves and full data set changes still invalidate them. Adds a Replace case to the ItemSpacing theory and a device test that replaces an off-screen item and checks that no item offsets are recomputed.
This comment has been minimized.
This comment has been minimized.
|
Merged net11 in 36d0085 (no conflicts). The rebase bot fails on this branch because it already has a merge commit. |
kubaflo
left a comment
There was a problem hiding this comment.
@marcelomoresco but could you please include videos with issue before and after the fix. And the table with benchmarks. Both in PR description
This comment has been minimized.
This comment has been minimized.
|
/rebase |
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
PR Test Gate
🧪 Gate analysis — click to expand⚠ Inconclusive. Setup, build, or execution did not produce a conclusive result. This does not prove the fix is incorrect. No interpretable test-group summary was produced. No additional test execution is inferred. Setup did not capture a verified PR head; no commit is claimed as tested. No immutable without-fix baseline was prepared. |
|
@kubaflo added before/after videos (GIFs, with MP4 links) and the benchmark table to the PR description. |
|
|
||
| // 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; |
There was a problem hiding this comment.
[moderate] CollectionView - Android - This reads the live adapter count, not a count synchronized with consumed notifications. ItemsSourceFactory leaves observable IEnumerable sources without IList unwrapped, and ObservableItemsSource dispatches their notifications while counting the live source. With one rendered item and ItemSpacing = 8, a worker can append twice after base.OnLayout computes the original item's zero bottom offset but before this read. ItemCount is then seeded with 3 while both insertions are queued. Their callbacks increment it to 4 and 5, so their exclusive ends 2 and 3 both fail ReachesLastRow and neither invalidates the original item's cached offsets. The subsequent layout resets the count without dirtying those offsets, leaving the half-spacing defect. Seed from notification-synchronized state, or preserve the unknown-count fallback when pending notifications cannot be excluded, and cover this layout/source interleaving.
There was a problem hiding this comment.
Same point as #40318 (comment): base.OnLayout reads the same live count for RecyclerView's own layout, so a source changed off the UI thread in that window is already out of sync with RecyclerView. Keeping it as is.
…ved at runtime (#40318) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Since #27093 and #34664, `SpacingItemDecoration` drops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (from `LayoutParams`) with its new position, so inserting or removing at the start misplaced the rows. - `MauiRecyclerView` watches the items adapter with the existing `DataChangeObserver` and calls `InvalidateItemDecorations()` only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout. `CollectionViewItemSpacingBenchmark` in Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped. - In pre-layout, `SpacingItemDecoration` takes the span index from the `SpanSizeLookup` instead of the `LayoutParams`. #### Tests New device test `CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime` (list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it. `ReplacingAnItemDoesNotRecomputeOtherItemOffsets` checks that replacing an off-screen item recomputes no other offsets. The full Android `CollectionViewTests` (152 passed) and `CarouselViewTests` (14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass. #### Before / After `ItemSpacing = 40` (gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator: | Before | After | |---|---| |  |  | Videos: [before.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/before.mp4), [after.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/after.mp4) #### Benchmarks `CollectionViewItemSpacingBenchmark` (Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked): | ItemSpacing = 8 | before (net11) | after | |---|---|---| | Append at end | 145 µs | 322 µs | | Append at end, 2-column grid | 498 µs | 1,059 µs | | Insert at start | 556 µs | 571 µs | | Replace off-screen item | 180 µs | 187 µs | Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing. ### Issues Fixed Fixes #40317 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ved at runtime (#40318) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Since #27093 and #34664, `SpacingItemDecoration` drops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (from `LayoutParams`) with its new position, so inserting or removing at the start misplaced the rows. - `MauiRecyclerView` watches the items adapter with the existing `DataChangeObserver` and calls `InvalidateItemDecorations()` only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout. `CollectionViewItemSpacingBenchmark` in Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped. - In pre-layout, `SpacingItemDecoration` takes the span index from the `SpanSizeLookup` instead of the `LayoutParams`. #### Tests New device test `CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime` (list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it. `ReplacingAnItemDoesNotRecomputeOtherItemOffsets` checks that replacing an off-screen item recomputes no other offsets. The full Android `CollectionViewTests` (152 passed) and `CarouselViewTests` (14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass. #### Before / After `ItemSpacing = 40` (gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator: | Before | After | |---|---| |  |  | Videos: [before.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/before.mp4), [after.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/after.mp4) #### Benchmarks `CollectionViewItemSpacingBenchmark` (Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked): | ItemSpacing = 8 | before (net11) | after | |---|---|---| | Append at end | 145 µs | 322 µs | | Append at end, 2-column grid | 498 µs | 1,059 µs | | Insert at start | 556 µs | 571 µs | | Replace off-screen item | 180 µs | 187 µs | Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing. ### Issues Fixed Fixes #40317 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ved at runtime (#40318) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Since #27093 and #34664, `SpacingItemDecoration` drops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (from `LayoutParams`) with its new position, so inserting or removing at the start misplaced the rows. - `MauiRecyclerView` watches the items adapter with the existing `DataChangeObserver` and calls `InvalidateItemDecorations()` only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout. `CollectionViewItemSpacingBenchmark` in Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped. - In pre-layout, `SpacingItemDecoration` takes the span index from the `SpanSizeLookup` instead of the `LayoutParams`. #### Tests New device test `CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime` (list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it. `ReplacingAnItemDoesNotRecomputeOtherItemOffsets` checks that replacing an off-screen item recomputes no other offsets. The full Android `CollectionViewTests` (152 passed) and `CarouselViewTests` (14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass. #### Before / After `ItemSpacing = 40` (gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator: | Before | After | |---|---| |  |  | Videos: [before.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/before.mp4), [after.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/after.mp4) #### Benchmarks `CollectionViewItemSpacingBenchmark` (Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked): | ItemSpacing = 8 | before (net11) | after | |---|---|---| | Append at end | 145 µs | 322 µs | | Append at end, 2-column grid | 498 µs | 1,059 µs | | Insert at start | 556 µs | 571 µs | | Replace off-screen item | 180 µs | 187 µs | Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing. ### Issues Fixed Fixes #40317 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ved at runtime (#40318) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Since #27093 and #34664, `SpacingItemDecoration` drops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (from `LayoutParams`) with its new position, so inserting or removing at the start misplaced the rows. - `MauiRecyclerView` watches the items adapter with the existing `DataChangeObserver` and calls `InvalidateItemDecorations()` only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout. `CollectionViewItemSpacingBenchmark` in Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped. - In pre-layout, `SpacingItemDecoration` takes the span index from the `SpanSizeLookup` instead of the `LayoutParams`. #### Tests New device test `CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime` (list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it. `ReplacingAnItemDoesNotRecomputeOtherItemOffsets` checks that replacing an off-screen item recomputes no other offsets. The full Android `CollectionViewTests` (152 passed) and `CarouselViewTests` (14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass. #### Before / After `ItemSpacing = 40` (gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator: | Before | After | |---|---| |  |  | Videos: [before.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/before.mp4), [after.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/after.mp4) #### Benchmarks `CollectionViewItemSpacingBenchmark` (Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked): | ItemSpacing = 8 | before (net11) | after | |---|---|---| | Append at end | 145 µs | 322 µs | | Append at end, 2-column grid | 498 µs | 1,059 µs | | Insert at start | 556 µs | 571 µs | | Replace off-screen item | 180 µs | 187 µs | Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing. ### Issues Fixed Fixes #40317 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ved at runtime (#40318) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 Since #27093 and #34664, `SpacingItemDecoration` drops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (from `LayoutParams`) with its new position, so inserting or removing at the start misplaced the rows. - `MauiRecyclerView` watches the items adapter with the existing `DataChangeObserver` and calls `InvalidateItemDecorations()` only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout. `CollectionViewItemSpacingBenchmark` in Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped. - In pre-layout, `SpacingItemDecoration` takes the span index from the `SpanSizeLookup` instead of the `LayoutParams`. #### Tests New device test `CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime` (list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it. `ReplacingAnItemDoesNotRecomputeOtherItemOffsets` checks that replacing an off-screen item recomputes no other offsets. The full Android `CollectionViewTests` (152 passed) and `CarouselViewTests` (14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass. #### Before / After `ItemSpacing = 40` (gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator: | Before | After | |---|---| |  |  | Videos: [before.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/before.mp4), [after.mp4](https://raw.githubusercontent.com/marcelomoresco/dotnet-maui/pr-assets/40318/after.mp4) #### Benchmarks `CollectionViewItemSpacingBenchmark` (Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked): | ItemSpacing = 8 | before (net11) | after | |---|---|---| | Append at end | 145 µs | 322 µs | | Append at end, 2-column grid | 498 µs | 1,059 µs | | Insert at start | 556 µs | 571 µs | | Replace off-screen item | 180 µs | 187 µs | Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing. ### Issues Fixed Fixes #40317 --------- Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
…ctionView enumeration (#40623) <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [X] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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. ### Root Cause The KeepItemsInView fix in #39491 introduced GetLayoutManager().ItemCount > 0 to avoid scrolling an empty collection. However, obtaining ItemCount for a grouped source counts every group. For enumerable-backed groups, this requires enumeration—even of groups unrelated to the insertion. Consequently, inserting into the first group unnecessarily enumerates the last group, violating the assertion in GroupedInsertWithoutScrollingAxisSpacingDoesNotCountAllGroups, introduced by #40318. The guard is redundant for this grouped path: the existing flat-index resolver locates the first data item without counting all groups. ### Description of Change Removes the `GetLayoutManager().ItemCount > 0` guard before the `KeepItemsInView` first-item scroll request introduced in #39491. For grouped sources, obtaining the adapter count walks every group and enumerates enumerable-backed groups. This adds unnecessary work when inserting into the first group The existing flat-index resolver already locates the first grouped data item, skipping empty leading groups and stopping once the target is found. A full adapter count is unnecessary. Insertion-only handling, non-animated scrolling, and header/group mapping remain unchanged. Removing the last ungrouped item does not trigger this path, because removal notifications are not treated as insertions. ### Issues Fixed Related: #39491 and #40318. **Test coverage** The existing device test `GroupedInsertWithoutScrollingAxisSpacingDoesNotCountAllGroups` covers this regression with cross-axis spacing values of `0` and `8`. No new test was added because this existing test directly covers the unnecessary full-count enumeration addressed by this fix. ### Tested the behaviour in the following platforms - [x] Android - [ ] Windows - [ ] iOS - [ ] Mac ### Output Screenshot Before Issue Fix | After Issue Fix | |----------|----------| |<image width="100" height="200" alt="Before Fix video" src="https://github.com/user-attachments/assets/361741a2-b54b-4b7c-a925-8a5bba16b945">|<image width="100" height="200" alt="After Fix video" src="https://github.com/user-attachments/assets/33bc9ae7-f631-4d88-a33f-0011a10f4b29">| Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
…p the zero-spacing item decoration (#40901) <!-- copilot-assessment:v1 --> ### 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).<br>↑ 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).<br>↑ A trace shows the removed work gone (selection 2.2% and GetItemOffsets 0.8% of UI-thread samples, both to 0), with allocations unchanged.<br>↓ No speed-up is measurable on the emulator, and the A/B included a third commit that is no longer part of this PR.<br>↓ Android UI tests, CI and physical devices not run yet.<br>↓ OnSelectedChanged is no longer called on bind or recycle when the selection doesn't change, which a custom SelectableViewHolder subclass could notice. | <!-- /copilot-assessment --> <!-- Please let the below note in for people that find this PR --> > [!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](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from this PR and let us know in a comment if this change resolves your issue. Thank you! <!-- Open .NET 11 fix PRs against net11 for review; target main for next-major features. After approval, a maintainer manually retargets the fix PR to the active inflight branch and merges it directly there. Do not merge individual fixes into net11. Bots must not retarget or merge. Candidate integration into net11 and release/* changes are separate, explicitly coordinated release work. --> ### 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 | - [x] I selected the applicable base branch using the [contribution guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting). 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 <!-- Enter description of the fix in this section --> 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 #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](https://github.com/dotnet/maui/tree/simonrozsival-collectionview-scroll-benchmark/src/Controls/tests/CollectionViewScrollBenchmark), 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: ```csharp selectable.Clicked -= SelectableClickedHandler; selectable.UpdateIsSelected(false); ``` ### Issues Fixed <!-- Please make sure that there is a bug logged for the issue being fixed. The bug should describe the problem and how to reproduce it. --> None; this was found by profiling. Related: - #40881 also edits `SelectableItemsViewAdapter.cs`; see above. - #40318 (inflight/11.0.1xx-sr3) composes with the decoration change: its checks treat a missing decoration like a zero-spacing one. - #37337 is opt-in handler update batching. - #31591 re-syncs selection on click; that path is unchanged here. - #38969 and #39661 also changed the spacing decoration (its cost and its outer-edge spacing). ### 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. <!-- Verify the target branch follows the release workflow in docs/ReleaseBranchWorkflow.md. Infrastructure and documentation changes should target the branch where they apply. --> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
Target Branch
mainnet11, for reviewFor .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
Since #27093 and #34664,
SpacingItemDecorationdrops the spacing on the outer edges based on each item's position. RecyclerView caches decoration offsets and only recomputes them for items it rebinds or shifts, so after an append the previous last item keeps its bottom offset of 0 (half the spacing between the two), and after removing the last item the new last item keeps its bottom offset. In grids, the pre-layout pass also paired the item's old span index (fromLayoutParams) with its new position, so inserting or removing at the start misplaced the rows.MauiRecyclerViewwatches the items adapter with the existingDataChangeObserverand callsInvalidateItemDecorations()only when items are inserted or removed in the last row (RecyclerView already recomputes the offsets of items it rebinds or shifts, and of all items on a reset), and only when the spacing is non-zero and RecyclerView isn't computing a layout.CollectionViewItemSpacingBenchmarkin Benchmarks.Droid measures the cost. CarouselView uses its own decoration and is skipped.SpacingItemDecorationtakes the span index from theSpanSizeLookupinstead of theLayoutParams.Tests
New device test
CollectionViewTests.ItemSpacingIsUpdatedWhenItemsChangeAtRuntime(list and 2-column grid × append, insert at start, remove from end, remove from start), compared with the same items populated up front. 6 of 8 cases fail without the fix; all pass with it.ReplacingAnItemDoesNotRecomputeOtherItemOffsetschecks that replacing an off-screen item recomputes no other offsets. The full AndroidCollectionViewTests(152 passed) andCarouselViewTests(14/14) pass at 440 and 160 dpi, and the ItemSpacing UI tests Issue32048, Issue38321 and Issue38925 pass.Before / After
ItemSpacing = 40(gold is the spacing), tapping Add item three times and Remove last twice on an Android API 31 emulator:Videos: before.mp4, after.mp4
Benchmarks
CollectionViewItemSpacingBenchmark(Benchmarks.Droid), Android emulator API 31 arm64, BenchmarkDotNet mean, before and after in the same session (measured on feb9e59; the later commits only change how the item count is tracked):Only inserts/removes in the last row pay: one offsets pass over the visible items, which is what refreshes the previous last row's spacing.
Issues Fixed
Fixes #40317