Skip to content

[Android] Fix ArgumentOutOfRangeException when removing items from grouped CollectionView - #38341

Merged
kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Vignesh-SF3580:fix-38321
Sep 9, 2026
Merged

kubaflo merged 2 commits into
dotnet:inflight/currentfrom
Vignesh-SF3580:fix-38321

Conversation

@Vignesh-SF3580

@Vignesh-SF3580 Vignesh-SF3580 commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

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!

Issue Details

On Android, removing an item from a visible group in a grouped CollectionView using GridItemsLayout can cause an ArgumentOutOfRangeException. The issue occurs during RecyclerView's predictive layout. The spacing calculation uses an outdated item count, which can result in an invalid adapter position.

Regression PR: #35782

Root Cause

SpacingItemDecoration uses RecyclerView.State.ItemCount to determine the last item position. During item removal, state.ItemCount can still contain the previous item count while the adapter has already been updated. This causes the calculated position to be outside the current adapter range, which eventually results in an ArgumentOutOfRangeException.

Description of Change

On Android, updated SpacingItemDecoration to use consistent adapter state when calculating item positions and counts for SpanSizeLookup. The change ensures that the position and item count passed to SpanSizeLookup are obtained from the current adapter state, avoiding inconsistencies during CollectionView item updates. Added additional tests to cover item removal scenarios in a grouped CollectionView using GridItemsLayout and to verify that the collection updates correctly without throwing exceptions.

Issues Fixed

Fixes #38321

Screenshots

Before Issue Fix After Issue Fix
38321BeforeFix.mov
38321AfterFix.mov

…hrows ArgumentOutOfRangeException after an item is removed
@github-actions

github-actions Bot commented Sep 8, 2026

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 38341

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 38341"

@dotnet-policy-service dotnet-policy-service Bot added the partner/syncfusion Issues / PR's with Syncfusion collaboration label Sep 8, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

@Vignesh-SF3580 Vignesh-SF3580 changed the title [WIP] [Android] Fix ArgumentOutOfRangeException when removing items from grouped CollectionView [Android] Fix ArgumentOutOfRangeException when removing items from grouped CollectionView Sep 9, 2026
@sheiksyedm
sheiksyedm marked this pull request as ready for review September 9, 2026 12:05
Copilot AI lite review requested due to automatic review settings September 9, 2026 12:05
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
There may be pipelines that require an authorized user to comment /azp run to run.

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

The new Issue38321 UI test should be Android-only (to match the HostApp issue page’s platform scope), and the PR description currently claims an adapter-null fallback that the implementation does not perform.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

Fixes an Android crash in grouped CollectionView grid spacing calculation during RecyclerView predictive (pre-)layout by avoiding stale RecyclerView.State.ItemCount usage, and adds a UI regression test + HostApp repro page for issue #38321.

Changes:

  • Update SpacingItemDecoration.GetItemOffsets to use the attached adapter’s ItemCount and guard against invalid adapter positions.
  • Add a HostApp issue page (Issue38321) that reproduces grouped grid removals.
  • Add a corresponding UI test (Issue38321) validating repeated removals complete without crashing.
File summaries
File Description
src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs Uses adapter ItemCount (and validates position) to prevent pre-layout stale-count crashes.
src/Controls/tests/TestCases.HostApp/Issues/Issue38321.cs Adds a repro page with grouped grid + delayed removals to trigger predictive layout.
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38321.cs Adds a UI test that taps “Remove item” repeatedly and asserts expected completion text.
Review details
  • Files reviewed: 3/3 changed files
  • Comments generated: 3
  • Review effort level: Lite

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Sep 9, 2026
@MauiBot

This comment has been minimized.

@MauiBot

This comment has been minimized.

@MauiBot MauiBot removed the s/agent-review-in-progress AI review is currently running for this PR label Sep 9, 2026

@MauiBot MauiBot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

AI Review Summary

@Vignesh-SF3580 — new AI review results are available based on commit 60eb23f.

Gate Passed Confidence Low Platform Android


🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix

Gate Result: ✅ PASSED

Platform: ANDROID · Base: main · Merge base: f7bfa2a5

Test Without Fix (expect FAIL) With Fix (expect PASS)
🖥️ Issue38321 Issue38321 ✅ FAIL — 1515s ✅ PASS — 686s
🔴 Without fix — 🖥️ Issue38321: FAIL ✅ · 1515s

Error-relevant lines (filtered from the build log):

   at UITest.Appium.NUnit.UITestBase.UITestBaseTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 159
   at UITest.Appium.NUnit.UITestBase.TestTearDown() in /_/src/TestUtils/src/UITest.NUnit/UITestBase.cs:line 45
🟢 With fix — 🖥️ Issue38321: PASS ✅ · 686s

(no coded error found; showing last 1200 chars)

A total of 1 test files matched the specified pattern.
[xUnit.net 00:00:00.00] xUnit.net VSTest Adapter v2.8.2+699d445a1a (64-bit .NET 10.0.13)
[xUnit.net 00:00:00.13]   Discovering: Controls.TestCases.Android.Tests
[xUnit.net 00:00:00.44]   Discovered:  Controls.TestCases.Android.Tests
NUnit Adapter 4.5.0.0: Test execution started
Running selected tests in /home/vsts/work/1/s/artifacts/bin/Controls.TestCases.Android.Tests/Debug/net10.0/Controls.TestCases.Android.Tests.dll
   NUnit3TestExecutor discovered 1 of 1 NUnit test cases using Current Discovery mode, Non-Explicit run
>>>>> 09/09/2026 18:12:55 FixtureSetup for Issue38321(Android)
>>>>> 09/09/2026 18:12:58 GroupedCollectionViewRemovalsUseCurrentAdapterPositions Start
>>>>> 09/09/2026 18:13:07 GroupedCollectionViewRemovalsUseCurrentAdapterPositions Stop
  Passed GroupedCollectionViewRemovalsUseCurrentAdapterPositions [8 s]
NUnit Adapter 4.5.0.0: Test execution complete
Results File: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38321.trx
Test Run Successful.
Total tests: 1
     Passed: 1
 Total time: 24.2569 Seconds
>>> TRX_RESULT_FILE: /home/vsts/work/1/s/CustomAgentLogsTmp/UITests/TestResults/Issue38321.trx
📁 Fix files reverted (1 files)
  • src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs

📋 Pre-Flight — Context & Validation

PR #38341 Pre-Flight

Context

  • PR: [Android] Fix ArgumentOutOfRangeException when removing items from grouped CollectionView
  • Issue: #38321, a verified regression introduced in 10.0.100 by #35782 and targeted for .NET 10 SR11.
  • Platform: Android. src/Controls/src/Core/Handlers/Items/Android/ is the sole active Android CollectionView handler; Items2 is iOS/MacCatalyst-only.
  • Scenario: Removing a visible item from a grouped CollectionView using GridItemsLayout triggers RecyclerView predictive pre-layout. RecyclerView.State.ItemCount can still describe the previous layout while the adapter and grouped source already expose the new count.
  • Failure chain: SpacingItemDecoration.GetItemOffsets passes stale state.ItemCount - 1 to SpanSizeLookup.GetSpanGroupIndex; that calls GridLayoutSpanSizeLookup.GetSpanSize, then adapter.GetItemViewType, and grouped-source index resolution reads beyond _groups, throwing ArgumentOutOfRangeException.

Existing PR Change

The PR replaces state.ItemCount with parent.GetAdapter().ItemCount, returns when the adapter is absent, and rejects child positions outside the adapter's current range. This keeps the position and last-item count in the adapter's live coordinate space.

Changed files:

  • src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs — production fix.
  • src/Controls/tests/TestCases.HostApp/Issues/Issue38321.cs — grouped-grid reproduction page.
  • src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue38321.cs — removal UI test.

Validation Boundary

The prior gate already proved the regression and must not be rerun:

  • Without the production fix: Issue38321 failed.
  • With the PR fix: Issue38321 passed.

Each alternative candidate may run only:

pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38321"

No additional mandatory regression test filters were supplied. Do not run a full suite or repeat gate verification.

Candidate Constraints

  • Modify only the production file admitted by EstablishBrokenBaseline.ps1: src/Controls/src/Core/Handlers/Items/Android/SpacingItemDecoration.cs.
  • Preserve the full-span header/footer spacing behavior added by #35782.
  • Avoid the PR's live-adapter-count-and-position-range-guard mechanism.
  • Viable distinct hypotheses include suppressing unsafe outer-edge span lookup specifically during predictive pre-layout, or constraining only the stale last-position lookup to a valid current adapter coordinate without adopting the PR's complete mechanism.
  • This callback is a layout/scroll hot path: avoid allocations, LINQ, logging, and unrelated refactoring.
  • The worktree contains pre-existing CI harness changes outside the target file. They must remain untouched.

Gate and Review State

  • Gate: passed (fail without fix, pass with fix).
  • Regression cross-reference: clean; no recent labeled bug-fix overlap was detected.
  • Dedicated expert review is deferred to STEP 5b. Try-fix candidates perform only the skill's required inline expert self-review.

🔬 Code Review — Deep Analysis

Code Review — PR #38341

Independent Assessment

What this changes: SpacingItemDecoration.GetItemOffsets now obtains both the child position and terminal item count from the currently attached RecyclerView.Adapter. It returns before calling SpanSizeLookup when the adapter is absent or the child position is no longer valid in that adapter. The added HostApp page and UI test repeatedly remove the first, middle, and last items from a visible group in a two-column grouped grid.

Inferred motivation: During RecyclerView predictive layout, RecyclerView.State.ItemCount can retain the pre-removal count while GridLayoutSpanSizeLookup resolves positions through the already-updated adapter. Passing state.ItemCount - 1 into that lookup can therefore address an item beyond the adapter's current range.

Approach assessment: Sound. Keeping the position, bounds check, and terminal item count in the adapter's live coordinate space removes the inconsistent-state access rather than merely clamping one symptom. The adapter-null, empty-adapter, NoPosition, and removed-last-child cases all return before the span lookup. The callback remains allocation-free and localized to the active Android CollectionView handler.

Reconciliation with PR Narrative

The current title and description accurately identify the Android grouped-CollectionView removal crash, the stale RecyclerView.State.ItemCount root cause, the adapter-consistent fix, regression #35782, and issue #38321. The code and narrative agree.

Prior Review Reconciliation

No prior ❌ Error findings were found.

Prior concern Source Status Evidence
Make the UI test Android-only Copilot inline review 🔄 Obsolete Repository UI-test guidance says tests run on all applicable platforms by default and the infrastructure handles platform detection. The test itself uses no Android-only API.
Description claimed a state.ItemCount fallback Copilot inline review ✅ Fixed The current description says the method uses consistent adapter state and no longer claims a fallback.
Add a matching #endif Copilot inline review 🔄 Obsolete This was contingent on adding the rejected Android-only #if; the submitted file has no unmatched directive.

Blast Radius Assessment

  • Runs for all instances: Yes. The decoration runs for Android CollectionViews using linear or grid layouts, but the new adapter validity checks are valid for grouped and ungrouped sources and preserve normal-layout spacing calculations.
  • Startup impact: None; this executes only while RecyclerView requests item offsets.
  • Static/shared state: None.
  • Handler lifecycle: A detached adapter is handled by the null return, and no subscriptions or retained state are introduced.

CI Status

  • Required-check result: Undetermined; gh pr checks 38341 --required could not authenticate in this environment.
  • Trusted Gate evidence: Passed — the supplied gate established that Issue38321 fails without the production fix and passes with it.
  • Classification: No PR-caused failure is known. Required-check visibility remains unavailable, so the code-review confidence is capped at low under the skill contract.

Findings

No actionable findings. The expert reviewer wrote [] to inline-findings.json.

Failure-Mode Probing

  • Removed view during predictive layout: NoPosition or a position at/above the live adapter count returns before GetSpanGroupIndex, preventing the stale grouped-source access.
  • Adapter absent or emptied during teardown/update: The null or bounds guard returns before computing itemCount - 1.
  • Linear and ungrouped layouts: They use the same valid live position/count pair; no grid-only assumption is introduced.
  • Disconnect/reconnect and null platform state: The callback receives the current parent; a missing adapter is explicitly safe, and no handler or static state is retained.
  • Adjacent spacing behavior: Valid positions still receive the same offsets and full-span-aware first/last row calculation introduced by #35782.

External Output Contract

Not applicable.

Verdict: NEEDS_DISCUSSION

Confidence: low

Summary: The submitted code is correct for the reproduced failure and the expert review found no actionable issue. The verdict is limited to NEEDS_DISCUSSION only because required-check status could not be retrieved; the independently supplied regression Gate passed.


🛠️ Try-Fix — Analysis & Comparison

Alternative Fix Candidates for PR #38341

Candidate 1 — Predictive Pre-Layout Timing Gate

Model: gpt-5.3-codex

Approach: Preserve #35782's full-span-aware outer-edge calculation during normal layout, but suppress the unsafe trailing-edge span-group lookup during RecyclerView predictive pre-layout. This targets the lifecycle window in which RecyclerView.State.ItemCount belongs to the previous layout.

Difference from the PR: The PR switches to adapter.ItemCount and validates the child adapter position against that live count. Candidate 1 instead avoids resolving the terminal span group during the inconsistent pre-layout phase; it does not adopt the PR's live-count/range-guard mechanism.

Result: Blocked

The required EstablishBrokenBaseline.ps1 invocation rejected the pre-existing dirty working directory before creating .github/.baseline-state.json. Per the try-fix restoration contract, the candidate did not edit production code and did not run the UI test. The exact restore command was still run and reported No baseline state found / Restored False, which is the expected no-state blocked path.

Files changed: None.

Diff: Empty.

Test: pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38321" — not executed because baseline establishment was blocked.

Self-review: 0 findings; no candidate diff existed to review.

Artifacts: CustomAgentLogsTmp/PRState/38341/PRAgent/try-fix/attempt-1/

Detailed report: CustomAgentLogsTmp/PRState/38341/PRAgent/try-fix-1/content.md

Candidate 2

Model: gpt-5.6-sol

Approach: Retain RecyclerView.State.ItemCount as the callback's layout coordinate space, but normalize only the synthesized terminal position passed to SpanSizeLookup.GetSpanGroupIndex to the current adapter terminal. If the adapter is absent or empty, skip that unsafe terminal lookup.

Difference from earlier approaches: Unlike the PR, this candidate would not replace the method's item count wholesale or reject every child position against the adapter count. Unlike Candidate 1, it would not suppress lookup during predictive pre-layout. It would keep the lookup active but bound only the stale terminal argument that reaches grouped-source indexing.

Result: Blocked

The required EstablishBrokenBaseline.ps1 invocation again rejected the pre-existing dirty working directory before creating .github/.baseline-state.json. The candidate therefore made no production changes and did not run the UI test. The exact restore command was run and reported No baseline state found / Restored False, which is the expected no-state blocked path.

Files changed: None.

Diff: Empty.

Test: pwsh .github/scripts/BuildAndRunHostApp.ps1 -Platform android -TestFilter "Issue38321" — not executed because baseline establishment was blocked.

Self-review: 0 findings; no candidate diff existed to review.

Artifacts: CustomAgentLogsTmp/PRState/38341/PRAgent/try-fix/attempt-2/

Detailed report: CustomAgentLogsTmp/PRState/38341/PRAgent/try-fix-2/content.md

Aggregate Outcome

Two bounded, mechanism-distinct alternatives were designed, but neither could be implemented or empirically tested because the authoritative baseline script rejected pre-existing tracked CI harness changes outside the target file. Both attempts honored the safety contract, captured Blocked artifacts, ran the required restore command, and left SpacingItemDecoration.cs identical to HEAD. The existing PR remains the only gate-validated implementation in this workspace.


🏁 Report — Final Recommendation

✅ Final Recommendation: APPROVE

Winning candidate: pr

The submitted PR is the only implemented candidate with direct regression evidence: the trusted Gate proved that Issue38321 fails without the production change and passes with it. The expert reviewer found no actionable correctness, performance, lifecycle, or test-quality issue, and inline-findings.json is an empty JSON array.

Candidate comparison

Rank Candidate Implementation Regression validation Assessment
1 pr Uses the current adapter for both ItemCount and child-position bounds before invoking SpanSizeLookup. Passed — fail without fix, pass with fix. Best evidence and the most coherent fix: all positions passed into adapter-backed span lookup use the same live coordinate space.
2 pr-plus-reviewer No reviewer change; reviewer.patch is empty and the candidate is behaviorally identical to pr. Not rerun because there was no refinement; it inherits the same submitted code already exercised by the Gate. Safe but provides no improvement over pr, so the raw candidate wins the tie.
3 try-fix-1 Proposed suppressing the terminal span-group lookup during predictive pre-layout. No diff was produced. Blocked before execution by baseline establishment. Mechanism-distinct, but unimplemented and unvalidated; it could also omit trailing-edge spacing during predictive layout rather than making lookup coordinates consistent.
4 try-fix-2 Proposed clamping only the terminal lookup position while retaining RecyclerView.State.ItemCount. No diff was produced. Blocked before execution by baseline establishment. More targeted than candidate 1, but unimplemented and unvalidated; it leaves position/count calculations split across state and adapter coordinate spaces.

Why pr wins

  • It fixes the demonstrated stale-count failure at its source by preventing adapter-backed lookup with an adapter-invalid position.
  • It preserves the full-span group-header/footer row calculation introduced by #35782 for all valid positions.
  • It handles adapter-null, empty-adapter, NoPosition, and removed-last-child cases without allocations in the layout hot path.
  • Its UI scenario exercises repeated first, middle, and last removals in the grouped two-column grid, and the trusted Gate confirms the regression boundary.
  • Neither try-fix candidate produced code or test evidence, and the expert pass supplied nothing that would justify changing the PR.

Review and CI notes

Prior Copilot concerns do not block this result: the stale description claim was corrected, and repository guidance explicitly defaults UI tests to all applicable platforms with infrastructure-managed platform detection. Required GitHub check status could not be queried because gh is unauthenticated in this environment; this is an evidence-visibility limitation, not a known PR failure. The supplied trusted Gate permits approval and the expert review contains no blocking code issue or unresolved discussion item.


📱 UI Tests — CollectionView

Detected UI test categories: CollectionView

⚠️ Deep UI tests — The deep UI run for 1 category (CollectionView) exceeded the per-category time budget (a very long-running category or a slow build/deploy) and was stopped before finishing. This is an infrastructure/timeout issue, not a code problem; re-run the review, and if a category consistently needs more time the per-category budget can be raised (DEEP_UITEST_CATEGORY_CAP_MIN / DEEP_UITEST_HARDSTOP_MIN). See the build-output.log in the drop-deep-uitests artifact.


🧭 Next Steps — review latest findings

No alternative fix was selected for this run. Review the session findings and CI results before merging.

@MauiBot MauiBot added the s/agent-changes-requested AI agent recommends changes - found a better alternative or issues label Sep 9, 2026
@MauiBot MauiBot added s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review) labels Sep 9, 2026
@kubaflo
kubaflo changed the base branch from main to inflight/current September 9, 2026 21:57
@kubaflo
kubaflo merged commit a63059a into dotnet:inflight/current Sep 9, 2026
28 of 35 checks passed
@github-actions github-actions Bot added this to the .NET 10 SR11 milestone Sep 9, 2026
kubaflo pushed a commit that referenced this pull request Sep 9, 2026
…ouped CollectionView (#38341)

> [!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!

### Issue Details
On Android, removing an item from a visible group in a grouped
CollectionView using GridItemsLayout can cause an
ArgumentOutOfRangeException. The issue occurs during RecyclerView's
predictive layout. The spacing calculation uses an outdated item count,
which can result in an invalid adapter position.

**Regression PR:** #35782

### Root Cause
SpacingItemDecoration uses RecyclerView.State.ItemCount to determine the
last item position. During item removal, state.ItemCount can still
contain the previous item count while the adapter has already been
updated. This causes the calculated position to be outside the current
adapter range, which eventually results in an
ArgumentOutOfRangeException.

### Description of Change
On Android, updated SpacingItemDecoration to use consistent adapter
state when calculating item positions and counts for SpanSizeLookup. The
change ensures that the position and item count passed to SpanSizeLookup
are obtained from the current adapter state, avoiding inconsistencies
during CollectionView item updates. Added additional tests to cover item
removal scenarios in a grouped CollectionView using GridItemsLayout and
to verify that the collection updates correctly without throwing
exceptions.

### Issues Fixed
Fixes #38321

### Screenshots

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/7d5e369f-127a-4a1e-a612-a10175f11286">
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/402a6790-45d3-40e3-9063-e3308eaca50b">
|
kubaflo pushed a commit that referenced this pull request Sep 11, 2026
…ouped CollectionView (#38341)

> [!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!

### Issue Details
On Android, removing an item from a visible group in a grouped
CollectionView using GridItemsLayout can cause an
ArgumentOutOfRangeException. The issue occurs during RecyclerView's
predictive layout. The spacing calculation uses an outdated item count,
which can result in an invalid adapter position.

**Regression PR:** #35782

### Root Cause
SpacingItemDecoration uses RecyclerView.State.ItemCount to determine the
last item position. During item removal, state.ItemCount can still
contain the previous item count while the adapter has already been
updated. This causes the calculated position to be outside the current
adapter range, which eventually results in an
ArgumentOutOfRangeException.

### Description of Change
On Android, updated SpacingItemDecoration to use consistent adapter
state when calculating item positions and counts for SpanSizeLookup. The
change ensures that the position and item count passed to SpanSizeLookup
are obtained from the current adapter state, avoiding inconsistencies
during CollectionView item updates. Added additional tests to cover item
removal scenarios in a grouped CollectionView using GridItemsLayout and
to verify that the collection updates correctly without throwing
exceptions.

### Issues Fixed
Fixes #38321

### Screenshots

| Before Issue Fix | After Issue Fix |
|----------|----------|
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/7d5e369f-127a-4a1e-a612-a10175f11286">
| <video width="300" height="600"
src="https://github.com/user-attachments/assets/402a6790-45d3-40e3-9063-e3308eaca50b">
|
@kubaflo

kubaflo commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

/backport to release/10.0.1xx-sr11

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/10.0.1xx-sr11 (link to workflow run)

@kubaflo

kubaflo commented Sep 12, 2026

Copy link
Copy Markdown
Contributor

/backport to main

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to main (link to workflow run)

kubaflo added a commit that referenced this pull request Sep 12, 2026
…from grouped CollectionView (#38486)

Backport of #38341 to main

/cc @kubaflo @Vignesh-SF3580

Co-authored-by: Vignesh-SF3580 <102575140+Vignesh-SF3580@users.noreply.github.com>
Co-authored-by: Jakub Florkowski <42434498+kubaflo@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 12, 2026
…n removing items from grouped CollectionView (#38482)

Backport of #38341 to release/10.0.1xx-sr11

/cc @kubaflo @Vignesh-SF3580

Co-authored-by: Vignesh-SF3580 <102575140+Vignesh-SF3580@users.noreply.github.com>
kubaflo pushed a commit that referenced this pull request Sep 29, 2026
…acingItemDecoration + ObservableGroupedSource) (#38969)

> [!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!

### Issue Details
On Android, a `CollectionView` with `GridItemsLayout` blocks the UI
thread for tens of seconds (and ANRs on fling) once the item count
reaches a few thousand. Assigning 10 000 grouped items: 94 ms on 10.0.90
→ ~40 s on 10.0.100+. Ungrouped grids regressed ~12× and stutter on
fling. Independently, `ScrollTo` a far group in a grouped grid took ~38
s for 10 000 items on every version.

### Root Cause
1. #35782 changed `SpacingItemDecoration.GetItemOffsets` to call
`SpanSizeLookup.GetSpanGroupIndex(itemCount - 1)` for **every cell on
every layout pass**. That is the uncached AndroidX API: it iterates
`getSpanSize()` (a JNI round-trip into `GridLayoutSpanSizeLookup`) over
every position between the nearest cached key and the target — O(n) per
cell. #38341 later fixed a crash on this path but not the cost.
2. `ObservableGroupedSource.GetGroupAndIndex` stepped one position at a
time (O(position)). It is reached from `GetItemViewType` for every
span-size query, so grouped grids paid O(n²) and any `ScrollTo` to an
uncached region was quadratic.

### Description of Change
- `SpacingItemDecoration`: return early when both offsets are 0; decide
first/last row by inspecting only the ≤ spanCount items that can share
the row, starting from the span index `GridLayoutManager` already
assigned to the child (`LayoutParams.SpanIndex`, falling back to
`GetSpanIndex`). Output is unchanged.
- `ObservableGroupedSource.GetGroupAndIndex`: walk groups with live
counts (O(groups)). Live counts are required because
`ReorderableItemsViewAdapter.OnItemMove` mutates groups with
`ObserveChanges` disabled. Empty groups without a header are now
resolved correctly (the old loop returned the empty group's index for
the next group's first item) and out-of-range positions no longer index
past `_groups`.

Not in this PR (follow-up candidate for #38926): overriding
`GetSpanIndex`/`GetSpanGroupIndex` in `GridLayoutSpanSizeLookup` so that
`GridLayoutManager` itself never walks `getSpanSize` across JNI for
uncached positions (ungrouped up-scroll after a jump still shows this).

### Measurements
HostApp `Issue38925` page (50 groups × 200 items, `Span=4`, spacing 4),
Release, HONOR PGT-N19 / Android 16. "UI thread blocked" measured from
the action until a `Dispatcher.Dispatch` callback runs.

| Step | `main` before | `main` with this PR |
|---|---|---|
| Set `ItemsSource` | 59 683 ms | **110 ms** |
| `ScrollTo` last group | 131 839 ms | **678 ms** |
| `ScrollTo` first group | 57 693 ms | **105 ms** |

| Before (4× speed) | After |
|---|---|
| <video
src="https://github.com/user-attachments/assets/dcb43c20-c088-4784-ad63-e921fa4d0ecb"
width="300"> | <video
src="https://github.com/user-attachments/assets/46baf477-5262-4c4e-9fcd-85976022dd65"
width="300"> |

Rendering verified unchanged: pixel-identical screen-recordings of the
grid region before/after on the same device; `Issue35700`'s existing
snapshot test covers grouped-grid spacing in CI.

### Tests
- `TestCases.HostApp/Issues/Issue38925.cs` +
`TestCases.Shared.Tests/Tests/Issues/Issue38925.cs` (Android): load 10
000 grouped items, `ScrollTo` end and start; each must complete within
the default wait. Fails before the fix (every step > 15 s), passes
after.
- `DeviceTests/.../CollectionViewTests.Android.cs`:
`GroupedSourceGetGroupAndIndexMatchesGroupContents` — 16
header/footer/group-header/group-footer combinations, including an empty
group, checked against a brute-force reference.

### Issues Fixed
Fixes #38925
Fixes #38926

### Validated on
- [x] Android
- [ ] iOS (not applicable — Android handler only)
- [ ] Mac (not applicable)
- [ ] Windows (not applicable)
kubaflo pushed a commit that referenced this pull request Oct 3, 2026
…acingItemDecoration + ObservableGroupedSource) (#38969)

> [!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!

### Issue Details
On Android, a `CollectionView` with `GridItemsLayout` blocks the UI
thread for tens of seconds (and ANRs on fling) once the item count
reaches a few thousand. Assigning 10 000 grouped items: 94 ms on 10.0.90
→ ~40 s on 10.0.100+. Ungrouped grids regressed ~12× and stutter on
fling. Independently, `ScrollTo` a far group in a grouped grid took ~38
s for 10 000 items on every version.

### Root Cause
1. #35782 changed `SpacingItemDecoration.GetItemOffsets` to call
`SpanSizeLookup.GetSpanGroupIndex(itemCount - 1)` for **every cell on
every layout pass**. That is the uncached AndroidX API: it iterates
`getSpanSize()` (a JNI round-trip into `GridLayoutSpanSizeLookup`) over
every position between the nearest cached key and the target — O(n) per
cell. #38341 later fixed a crash on this path but not the cost.
2. `ObservableGroupedSource.GetGroupAndIndex` stepped one position at a
time (O(position)). It is reached from `GetItemViewType` for every
span-size query, so grouped grids paid O(n²) and any `ScrollTo` to an
uncached region was quadratic.

### Description of Change
- `SpacingItemDecoration`: return early when both offsets are 0; decide
first/last row by inspecting only the ≤ spanCount items that can share
the row, starting from the span index `GridLayoutManager` already
assigned to the child (`LayoutParams.SpanIndex`, falling back to
`GetSpanIndex`). Output is unchanged.
- `ObservableGroupedSource.GetGroupAndIndex`: walk groups with live
counts (O(groups)). Live counts are required because
`ReorderableItemsViewAdapter.OnItemMove` mutates groups with
`ObserveChanges` disabled. Empty groups without a header are now
resolved correctly (the old loop returned the empty group's index for
the next group's first item) and out-of-range positions no longer index
past `_groups`.

Not in this PR (follow-up candidate for #38926): overriding
`GetSpanIndex`/`GetSpanGroupIndex` in `GridLayoutSpanSizeLookup` so that
`GridLayoutManager` itself never walks `getSpanSize` across JNI for
uncached positions (ungrouped up-scroll after a jump still shows this).

### Measurements
HostApp `Issue38925` page (50 groups × 200 items, `Span=4`, spacing 4),
Release, HONOR PGT-N19 / Android 16. "UI thread blocked" measured from
the action until a `Dispatcher.Dispatch` callback runs.

| Step | `main` before | `main` with this PR |
|---|---|---|
| Set `ItemsSource` | 59 683 ms | **110 ms** |
| `ScrollTo` last group | 131 839 ms | **678 ms** |
| `ScrollTo` first group | 57 693 ms | **105 ms** |

| Before (4× speed) | After |
|---|---|
| <video
src="https://github.com/user-attachments/assets/dcb43c20-c088-4784-ad63-e921fa4d0ecb"
width="300"> | <video
src="https://github.com/user-attachments/assets/46baf477-5262-4c4e-9fcd-85976022dd65"
width="300"> |

Rendering verified unchanged: pixel-identical screen-recordings of the
grid region before/after on the same device; `Issue35700`'s existing
snapshot test covers grouped-grid spacing in CI.

### Tests
- `TestCases.HostApp/Issues/Issue38925.cs` +
`TestCases.Shared.Tests/Tests/Issues/Issue38925.cs` (Android): load 10
000 grouped items, `ScrollTo` end and start; each must complete within
the default wait. Fails before the fix (every step > 15 s), passes
after.
- `DeviceTests/.../CollectionViewTests.Android.cs`:
`GroupedSourceGetGroupAndIndexMatchesGroupContents` — 16
header/footer/group-header/group-footer combinations, including an empty
group, checked against a brute-force reference.

### Issues Fixed
Fixes #38925
Fixes #38926

### Validated on
- [x] Android
- [ ] iOS (not applicable — Android handler only)
- [ ] Mac (not applicable)
- [ ] Windows (not applicable)
kubaflo pushed a commit that referenced this pull request Oct 6, 2026
…acingItemDecoration + ObservableGroupedSource) (#38969)

> [!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!

### Issue Details
On Android, a `CollectionView` with `GridItemsLayout` blocks the UI
thread for tens of seconds (and ANRs on fling) once the item count
reaches a few thousand. Assigning 10 000 grouped items: 94 ms on 10.0.90
→ ~40 s on 10.0.100+. Ungrouped grids regressed ~12× and stutter on
fling. Independently, `ScrollTo` a far group in a grouped grid took ~38
s for 10 000 items on every version.

### Root Cause
1. #35782 changed `SpacingItemDecoration.GetItemOffsets` to call
`SpanSizeLookup.GetSpanGroupIndex(itemCount - 1)` for **every cell on
every layout pass**. That is the uncached AndroidX API: it iterates
`getSpanSize()` (a JNI round-trip into `GridLayoutSpanSizeLookup`) over
every position between the nearest cached key and the target — O(n) per
cell. #38341 later fixed a crash on this path but not the cost.
2. `ObservableGroupedSource.GetGroupAndIndex` stepped one position at a
time (O(position)). It is reached from `GetItemViewType` for every
span-size query, so grouped grids paid O(n²) and any `ScrollTo` to an
uncached region was quadratic.

### Description of Change
- `SpacingItemDecoration`: return early when both offsets are 0; decide
first/last row by inspecting only the ≤ spanCount items that can share
the row, starting from the span index `GridLayoutManager` already
assigned to the child (`LayoutParams.SpanIndex`, falling back to
`GetSpanIndex`). Output is unchanged.
- `ObservableGroupedSource.GetGroupAndIndex`: walk groups with live
counts (O(groups)). Live counts are required because
`ReorderableItemsViewAdapter.OnItemMove` mutates groups with
`ObserveChanges` disabled. Empty groups without a header are now
resolved correctly (the old loop returned the empty group's index for
the next group's first item) and out-of-range positions no longer index
past `_groups`.

Not in this PR (follow-up candidate for #38926): overriding
`GetSpanIndex`/`GetSpanGroupIndex` in `GridLayoutSpanSizeLookup` so that
`GridLayoutManager` itself never walks `getSpanSize` across JNI for
uncached positions (ungrouped up-scroll after a jump still shows this).

### Measurements
HostApp `Issue38925` page (50 groups × 200 items, `Span=4`, spacing 4),
Release, HONOR PGT-N19 / Android 16. "UI thread blocked" measured from
the action until a `Dispatcher.Dispatch` callback runs.

| Step | `main` before | `main` with this PR |
|---|---|---|
| Set `ItemsSource` | 59 683 ms | **110 ms** |
| `ScrollTo` last group | 131 839 ms | **678 ms** |
| `ScrollTo` first group | 57 693 ms | **105 ms** |

| Before (4× speed) | After |
|---|---|
| <video
src="https://github.com/user-attachments/assets/dcb43c20-c088-4784-ad63-e921fa4d0ecb"
width="300"> | <video
src="https://github.com/user-attachments/assets/46baf477-5262-4c4e-9fcd-85976022dd65"
width="300"> |

Rendering verified unchanged: pixel-identical screen-recordings of the
grid region before/after on the same device; `Issue35700`'s existing
snapshot test covers grouped-grid spacing in CI.

### Tests
- `TestCases.HostApp/Issues/Issue38925.cs` +
`TestCases.Shared.Tests/Tests/Issues/Issue38925.cs` (Android): load 10
000 grouped items, `ScrollTo` end and start; each must complete within
the default wait. Fails before the fix (every step > 15 s), passes
after.
- `DeviceTests/.../CollectionViewTests.Android.cs`:
`GroupedSourceGetGroupAndIndexMatchesGroupContents` — 16
header/footer/group-header/group-footer combinations, including an empty
group, checked against a brute-force reference.

### Issues Fixed
Fixes #38925
Fixes #38926

### Validated on
- [x] Android
- [ ] iOS (not applicable — Android handler only)
- [ ] Mac (not applicable)
- [ ] Windows (not applicable)
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 13, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

area-controls-collectionview CollectionView, CarouselView, IndicatorView community ✨ Community Contribution partner/syncfusion Issues / PR's with Syncfusion collaboration platform/android s/agent-changes-requested AI agent recommends changes - found a better alternative or issues s/agent-fix-pr-picked AI could not beat the PR fix - PR is the best among all candidates s/agent-gate-passed AI verified tests catch the bug (fail without fix, pass with fix) s/agent-reviewed PR was reviewed by AI agent workflow (full 4-phase review)

Projects

None yet

4 participants