[Android] Fix app crash caused by dynamic template switching in ListView #24808
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Root cause
In the ViewCellRenderer class, the platform view was being recreated for each cell without properly removing the existing parent view (i.e., the ViewCellContainer ) before attempting to add the new view. This caused an exception:'The specified child already has a parent. You must call removeView() on the child's parent first. 'The issue arose due to improper handling of the platform view's parent when switching between different DataTemplates in a ListView using the RetainElement caching strategy in .NET MAUI.
Description of Issue Fix
The fix involved checking if the platformView already had a parent (i.e., ViewGroup) and ensuring that the parent was removed before adding the platformView to the new container. By introducing this conditional check, the system prevents the platform view from being associated with multiple parents, which caused the "The specified child already has a parent" exception. This change ensures that dynamic template changes in the ListView are handled correctly, improving view recycling and maintaining stable rendering without conflicts.
Validated the behaviour in the following platforms
Issues Fixed
Fixes #24701
Output
Before fix:
After fix:
Testcase:
The Testcase is already available for this fix. Please refer to the PR link below for reference.
Clear out prototype cell when changing ItemSource by PureWeen · Pull Request #24700 · dotnet/maui (github.com)