Skip to content

Commit beb7c53

Browse files
[Android] Removing outdated menu items as Android can delete them after switching activities (#28767)
* Fixing issue #24357 by removing outdated menu items as Android can delete them after switching activities * Disposing outdated IMenuItem just in case * Reduced memory allocation * Tuned performance a bit
1 parent 90d1827 commit beb7c53

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/Controls/src/Core/Platform/Android/Extensions/ToolbarExtensions.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,9 +232,22 @@ public static void UpdateMenuItems(this AToolbar toolbar,
232232
if (sortedToolbarItems == null || previousMenuItems == null)
233233
return;
234234

235-
var context = mauiContext.Context;
236235
var menu = toolbar.Menu;
237236

237+
// menu items can be deleted by Android after switching activities, removing outdated menu items first
238+
if (menu != null)
239+
{
240+
for (var j = previousMenuItems.Count - 1; j >= 0; j--)
241+
{
242+
var previousMenuItem = previousMenuItems[j];
243+
if (menu.FindItem(previousMenuItem.ItemId) == null)
244+
{
245+
previousMenuItem.Dispose();
246+
previousMenuItems.RemoveAt(j);
247+
}
248+
}
249+
}
250+
238251
foreach (var toolbarItem in previousToolBarItems)
239252
toolbarItem.PropertyChanged -= toolbarItemChanged;
240253

0 commit comments

Comments
 (0)