Repository navigation
[Android] Keep CollectionView item views parented while their view holders are pooled - #40897
simonrozsival wants to merge 7 commits into
Conversation
… are pooled TemplatedItemViewHolder removed its view from the ItemsView's logical children whenever RecyclerView recycled the holder, and added it back on every bind. Each row brought into view ran the Element.SetParent cascade twice over the row and its descendants: style sheets, resources, Window and descendant events. A holder that's recycled while it still has an adapter position has been scrolled out of view. Its view now stays a logical child of the ItemsView while the holder is pooled, and binding it again only changes its BindingContext, as the Items2 handler does on iOS. The views of removed items, or of a data set that changed, still leave the logical tree when they're recycled. RecyclerView reports through PoolingContainer when it releases a pooled view: the pool is full or cleared, or the adapter changes. The holder removes its view from the logical tree then. When RecyclerView is detached from the window it also releases its children and the holders it caches, and it shows them again without binding them; holders that are still bound to an adapter therefore keep their views. When a holder is bound to a different template, its old view leaves the logical tree. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
RecyclerViews that share a RecycledViewPool can bind each other's view holders. A pooled view now stays a logical child of the ItemsView that recycled it, so when another ItemsView binds its holder, the view leaves the previous ItemsView's logical children before it joins the new one. The same applies to the old view when a holder is bound to a different template. Add Android device tests for the views of pooled holders: they stay logical children while pooled, leave when RecyclerView releases them from its pool or their item is removed, stay parented while displayed or cached when RecyclerView is detached from the window, move between CollectionViews and templates, and don't keep a removed CollectionView alive. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
There was a problem hiding this comment.
Expert Review — 3 findings · ⚠️ 1 breaking change
Reviewed commit 7021f3a.
Warning
Existing apps would look or behave differently without opting in. See the Behavioral Change Disclosure findings at:
See inline comments for details.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
…ource Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
There was a problem hiding this comment.
Expert Review — No more findings
Reviewed commit 1407f45.
Selected Tests🧪 Test selection — click to expand
🧪 UI tests —
|
| Platform | Categories |
|---|---|
| Android | CarouselView, CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7 |
🧪 Device tests — Controls.CarouselView, Controls.CollectionView, Controls.Memory on Android
❌ Could not queue maui-pr-devicetests: Azure Pipelines did not start maui-pr-devicetests for the dispatch branch run-devicetests/pr40897-46566569688 within 10 minutes. Comment /review run-tests again, or use /azp run maui-pr-devicetests for the full suite.
GPT-6.2 Sol: Run Android device tests for CollectionView and CarouselView recycling, plus Controls memory coverage for retained views and handlers.
MAI Code 2: Android item-view pool and release changes; run CollectionView, CarouselView, and memory device tests on Android.
🧪 Running — 3 categories on Android
| Platform | Categories |
|---|---|
| Android | Controls.CarouselView, Controls.CollectionView, Controls.Memory |
⏭️ Skipped — what neither suite runs
UI tests — 69 categories, 3 platforms
Platforms not run: iOS, MacCatalyst, Windows
Categories not run: Accessibility, ActionSheet, ActivityIndicator, Animation, AppLinks, Border, BoxView, Brush, Button, Cells, CheckBox, ContextActions, CustomRenderers, DatePicker, Dispatcher, DisplayAlert, DisplayPrompt, DragAndDrop, Entry, Editor, Effects, Essentials, FlyoutPage, Focus, Fonts, Frame, Gestures, GraphicsView, Image, ImageButton, IndicatorView, InputTransparent, IsEnabled, IsVisible, Label, Layout, Lifecycle, ManualReview, Maps, Navigation, Page, Performance, Picker, ProgressBar, RadioButton, RefreshView, SafeAreaEdges, Shadow, ScrollView, SearchBar, Shape, Slider, SoftInput, Stepper, Switch, SwipeView, Shell1, Shell2, TabbedPage, TableView, TimePicker, TitleView, ToolbarItem, Triggers, ViewBaseTests, VisualStateManager, Window, WebView, Material3
Each skipped platform and category is listed as a maui-pr-uitests (skipped) … status on this commit. Use /azp run maui-pr-uitests for the full suite.
Device tests — 102 categories, 3 platforms
Platforms not run: iOS, MacCatalyst, Windows
Categories not run: Controls.Accessibility, Controls.Animations, Controls.Application, Controls.Behavior, Controls.Border, Controls.BoxView, Controls.Button, Controls.CheckBox, Controls.Compatibility, Controls.ContentView, Controls.DatePicker, Controls.Dispatcher, Controls.Editor, Controls.Element, Controls.Entry, Controls.FlexLayout, Controls.FlyoutPage, Controls.Frame, Controls.Gesture, Controls.HybridWebView, Controls.Image, Controls.Label, Controls.Layout, Controls.Lifecycle, Controls.Map, Controls.Mapper, Controls.MenuFlyout, Controls.Modal, Controls.NavigationPage, Controls.Page, Controls.PageTransitions, Controls.Path, Controls.Picker, Controls.RadioButton, Controls.RefreshView, Controls.ScrollView, Controls.SearchBar, Controls.Shape, Controls.Shell, Controls.Slider, Controls.SwipeView, Controls.Switch, Controls.TabbedPage, Controls.TemplatedView, Controls.TextInput, Controls.Toolbar, Controls.View, Controls.VisualElement, Controls.VisualElementTree, Controls.WebView, Controls.Window, Controls.WindowOverlay, Controls.Xaml, Core.ActivityIndicator, Core.Animation, Core.Application, Core.Border, Core.BoxView, Core.Button, Core.CheckBox, Core.ContentView, Core.DatePicker, Core.Dispatcher, Core.Editor, Core.Element, Core.Entry, Core.FlowDirection, Core.FlyoutView, Core.Fonts, Core.Formatting, Core.Graphics, Core.GraphicsView, Core.Image, Core.ImageButton, Core.ImageSource, Core.IndicatorView, Core.Label, Core.Layout, Core.Lifecycle, Core.MauiContext, Core.Memory, Core.NavigationPage, Core.Page, Core.Picker, Core.ProgressBar, Core.RadioButton, Core.RefreshView, Core.ScrollView, Core.SearchBar, Core.ShapeView, Core.Slider, Core.Stepper, Core.SwipeView, Core.Switch, Core.TimePicker, Core.View, Core.WebView, Core.Window, Core.WindowOverlay, Graphics, Essentials, BlazorWebView
Each skipped platform and project is listed as a maui-pr-devicetests (skipped) … status on this commit. Use /azp run maui-pr-devicetests for the full suite.
🤖 Why these tests — AI rationale (GPT-6.2 Sol + MAI Code 2)
UI tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, CarouselView |
CollectionView1, CollectionView2, CollectionView3, CollectionView4, CollectionView5, CollectionView6, CollectionView7, CarouselView |
| iOS | — | — |
| MacCatalyst | — | — |
| Windows | — | — |
GPT-6.2 Sol — Run Android CollectionView and CarouselView UI tests for the shared item recycling change.
- ItemsViewAdapter and MauiRecyclerView change how both controls recycle and rebind item views.
- The pool and holder changes are Android-only and do not affect unrelated controls or Material3 rendering.
MAI Code 2 — Android item-view pooling lifecycle changes; run CollectionView and CarouselView UI tests on Android.
- Android
Itemshandlers now retain and later release templated item views from the RecyclerView pool, directly affecting CollectionView recycling and logical-tree behavior. - The same Android Items adapter infrastructure is used by CarouselView, so its item binding and reuse behavior is covered.
- The change is Android-only; iOS, Mac Catalyst, and Windows UI tests are deliberately excluded.
- No full run is needed because the change is confined to item recycling rather than shared base, layout, startup, or build infrastructure.
Device tests
Each model chose independently; every test that runs was selected by at least one of them.
| Platform | GPT-6.2 Sol | MAI Code 2 |
|---|---|---|
| Android | Controls.CollectionView, Controls.CarouselView, Controls.Memory |
Controls.CollectionView, Controls.CarouselView, Controls.Memory |
| iOS | — | — |
| MacCatalyst | — | — |
| Windows | — | — |
GPT-6.2 Sol — Run Android device tests for CollectionView and CarouselView recycling, plus Controls memory coverage for retained views and handlers.
- CollectionViewTests.Android.cs adds pool retention and release cases.
- The Android Items handler shares recycling with CarouselView.
- Controls.Memory covers handler leaks for both controls; no Core or other platform code changed.
MAI Code 2 — Android item-view pool and release changes; run CollectionView, CarouselView, and memory device tests on Android.
src/Controls/src/Core/Handlers/Items/Androidchanges CollectionView and CarouselView holder pooling, logical parenting, and release behavior.- The modified Android CollectionView device tests directly validate pool trimming, replacement, resets, removals, and logical-child cleanup.
- Controls.Memory is included because retained logical item views can leak if pooled holders are not released correctly.
- Device testing is limited to Android; other platforms do not compile these files, and no full run or unrelated handler categories are needed.
Generated by /review run-tests. A targeted run is a fast signal, not full-suite certification.
MAUI Autopilot — Ready for maintainer reviewResults
|
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Agent assessment
Self-reported assessment, not an independent review.
Assessed revision:
7021f3af6d2ba7ad177164ece27a9d9a7c0a5205↑ 7 new device tests pass, and 5 of them fail with the product change reverted; CollectionViewTests (298 passed, 1 skipped) and CarouselViewTests (16/16) pass on an API 35 emulator.
↓ It changes when item views leave the logical tree, in code where #36058 reverted three PRs.
↓ First-scroll rebind time rose 18–29% across three comparisons (two significant), unexplained; warm-pass timing shows no significant gain against main.
↓ UI tests, other API levels, physical devices and CI not run yet.
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Target Branch
mainnet11, for 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
Why this is a draft
What changed
On Android,
CollectionView(theItemshandler) removed an item's view from theItemsView's logical children whenever RecyclerView recycled its view holder, and added it back on every bind. So every row scrolled into view ran theElement.SetParentcascade twice over the row and all its descendants: style sheets, resource lookups and propagation,Windowchanges, and child and descendant events. In the scroll benchmark below, that accounted for 39% of the UI thread's allocations, andElement.SetParentalone for 5.4% of its CPU samples.ItemsViewAdapter.OnViewRecycled: a holder recycled while it still has an adapter position was scrolled out of view. Its view now stays a logical child of theItemsViewwhile the holder is pooled, so binding it again only changes itsBindingContext. TheItems2handler already does this on iOS (TemplatedCell2.PrepareForReuse). The views of removed items, or of a data set that changed (AbsoluteAdapterPosition == NoPosition), still leave the logical tree when they're recycled.TemplatedItemViewHolderregisters an AndroidXPoolingContainerlistener on its item view. RecyclerView calls it when it releases a pooled view: when the pool is full and drops the holder, when the pool is cleared (adapter orItemTemplatechange, empty-view swap, handler teardown), and when RecyclerView is detached from the window. The view then leaves the logical tree, unless the holder is still bound to an adapter: on detach, RecyclerView also releases its displayed and cached holders, and it shows them again later without binding them.TemplatedItemViewHolder.Bindadds the view as a logical child only if it isn't one already. When the holder is bound to a different template, the old view leaves the logical tree. When anotherItemsViewbinds the holder (RecyclerViews that share a pool), the view moves to thatItemsView.EmptyViewAdapter,SimpleViewHolder) are unchanged. No public API changes.AndroidX.CustomView.PoolingContaineralready comes in throughXamarin.AndroidX.RecyclerView.Why it's safe
#36058 reverted three PRs in this code:
Dispose, and Fix CI failure for CollectionView Scrolling Feature Tests due to PR #35379 #35536 then guarded aRemoveViewcall on a disposed JNI handle.This PR doesn't disconnect, recreate or dispose anything, and it never touches native views. It only changes when the MAUI view leaves the logical tree, from RecyclerView's own callbacks on the UI thread. Views, handlers and their state are kept across recycling, as on main.
In RecyclerView 1.4.0's bytecode, I checked where RecyclerView calls PoolingContainer:
RecycledViewPool.putRecycledView(pool full),RecycledViewPool.clear(),RecycledViewPool.detachForPoolingContainer(no adapter attached any more), andonDetachedFromWindowof theRecycler(cached holders) and ofRecyclerView(displayed children). I also checked thatonViewRecycledruns before RecyclerView clears the holder's owner and adapter, soAbsoluteAdapterPositionis still valid there.Known gaps:
RecycledViewPool.SetMaxRecycledViewsdrops them without a release callback, so they stay logical children for theItemsView's lifetime. MAUI doesn't call it.OnViewRecycled, so its view stays parented. That's the same on main.Behavior changes
LogicalChildren,IVisualTreeElement.GetVisualChildren()and Hot Reload's visual tree until RecyclerView releases them, with their lastBindingContext, as on iOS (Items2).ChildAdded,ChildRemoved,DescendantAdded,DescendantRemovedand the VisualDiagnostics notifications no longer fire as the list scrolls.Windowand keep receiving resource, style, theme,FlowDirectionandVisualchanges.LoadedandUnloadeddon't change: they follow whether the native view is attached.ItemsViewto its page (0.2% of the UI thread's CPU samples in the profile).Results
The CollectionView scroll benchmark (pushed for reference; it isn't part of this or any PR) shows 1,000 items whose row is a
Gridof aBoxView, 7Labels, aProgressBarand aCheckBox, with 13 compiled bindings. Every pass scrolls 100 dp per frame for 240 frames and binds about 267 rows; the numbers are per row bound, on the UI thread. Each launch is a new process with a first scroll, a warm-up pass and 5 warm passes; a launch counts as the median of its warm passes. The variants ran interleaved for 12 rounds. The tables show the medians of the launches and the median paired difference with its 95% sign-test interval;*marks intervals that exclude zero.Device: Android emulator, Pixel 6 profile, Android 15 (API 35, google_apis arm64-v8a), 4 cores, 4 GB, on a shared, busy Apple silicon Mac (load average 20–30 during this run). .NET SDK 12.0.100-alpha.1.26523.103 (CoreCLR 12.0.0-alpha.1.26523.103), Release, android-arm64. Allocations, GC and JIT counts are exact; an A/A run on this setup gave timing intervals of about ±10% (UI thread CPU) to ±17% (rebind).
Against main bd40bc6. This PR was built from ca8fae27c4, which has the same product code as the head (the head only adds a test):
On top of #40881 (bf7161c), from the same run:
An earlier 12-round run of main against 332e8ba (the first commit; the second only matters when RecyclerViews share a pool), on a busier host (load average up to ~90), gave the same allocations and GC counts; UI thread CPU +40 µs/row [−170, +281]; rebind CPU +27.6 µs/row [+3.4, +38.8] (+14%) *; first-scroll rebind +98 µs/row [+12, +223] (+29%) *.
Profile (EventPipe sample profiler, one traced launch of each, 8 warm passes, 2,136 rows), UI thread CPU samples, main → this PR: all 1,223 → 956;
Element.SetParent66 → 0;NavigableElement.OnParentSet48 → 0;OnViewRecycled57 → 20;VisualElement.OnChildMeasureInvalidated1 → 2; the row'sBindingContextchange 190 → 175.We don't know yet why the first scroll's rebinds are slower. An unverified guess: the cascade used to run some of the same code right before each rebind, outside the timed window, so that code was already warm (or tiered up) when the rebind ran.
Tests
New Android device tests in
CollectionViewTests.Android.cs:ScrolledOutItemViewsStayLogicalChildrenWhilePooledItemViewsLeaveLogicalTreeWhenReleasedFromPoolDetachingFromWindowKeepsDisplayedAndCachedItemViewsParentedRemovedItemViewLeavesLogicalTreeTemplateChangeRemovesOldViewFromLogicalTreeHolderBoundByAnotherCollectionViewMovesItsViewPooledItemViewsDoNotLeak: pools views while they're still logical children, pops the page, and waits until theCollectionView, its handler, theRecyclerView, the item views and their handlers are collected.Run on the emulator above, in Release (the script's default):
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform android -IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests -DeviceUdid emulator-5610: Passed 298, Failed 0, Skipped 1 (CellSizeAccountsForMargin, skipped on Android), Total 299. Built from ca8fae27c4, beforePooledItemViewsDoNotLeakwas added.MemoryTests.HandlerDoesNotLeak(-IncludeClasses Microsoft.Maui.DeviceTests.CollectionViewTests,Microsoft.Maui.DeviceTests.Memory.MemoryTests, with the class-qualified test names in-IncludeMethods): with this PR, Passed 49, Failed 0. Withsrc/Controls/srcreverted to main: Passed 44, Failed 5. The failures are the 4 tests of the new parenting behavior andPooledItemViewsDoNotLeak, whose precondition (pooled views are still logical children) fails.DetachingFromWindow…andRemovedItemView…guard behavior that main already has, and pass on both.-IncludeClasses Microsoft.Maui.DeviceTests.CarouselViewTests: Passed 16, Failed 0, Total 16.Not run: UI tests (
maui-pr-uitests), the other Controls device tests, other Android API levels and physical devices; iOS, Mac Catalyst and Windows, since only Android files change. Hot Reload and VisualDiagnostics trees weren't checked by hand.Issues Fixed
None. Related: #34534, #35379 and #35536 (reverted by #36058), #35344, #34783, #32243 (open; this PR doesn't address it), #40881.
Let AI finish this PR