Merge pull request #150 from MathiasLopezNareia/android-popup-handler-null

Resolve crash when navigating to PopupPage after app is sent to background
This commit is contained in:
Tyson Elliot Hooker
2025-05-16 13:51:52 +10:00
committed by GitHub
2 changed files with 35 additions and 2 deletions

View File

@@ -0,0 +1,32 @@
namespace Mopups.Extensions;
public static class MauiExtensions
{
public static IMauiContext FindMauiContext(this Element element, bool fallbackToAppMauiContext = true)
{
if (element is IElement fe && fe.Handler?.MauiContext != null)
return fe.Handler.MauiContext;
foreach (var parent in element.GetParentsPath())
{
if (parent is IElement parentView && parentView.Handler?.MauiContext != null)
return parentView.Handler.MauiContext;
}
return fallbackToAppMauiContext ? Application.Current?.FindMauiContext() : default;
}
internal static IEnumerable<Element> GetParentsPath(this Element self)
{
Element current = self;
while (!IsApplicationOrNull(current.RealParent))
{
current = current.RealParent;
yield return current;
}
}
internal static bool IsApplicationOrNull(object? element) =>
element == null || element is IApplication;
}

View File

@@ -1,8 +1,9 @@
using Android.Views;
using Android.Views;
using Android.Widget;
using AndroidX.Activity;
using AndroidX.Fragment.App;
using AsyncAwaitBestPractices;
using Mopups.Extensions;
using Microsoft.Maui.Platform;
using Mopups.Interfaces;
using Mopups.Pages;
@@ -44,7 +45,7 @@ public class AndroidMopups : IPopupPlatform
page.Parent = MauiApplication.Current.Application.Windows[0].Content as Element;
page.Parent ??= MauiApplication.Current.Application.Windows[0].Content as Element;
var handler = page.Handler ??= new PopupPageHandler(page.Parent.Handler.MauiContext);
var handler = page.Handler ??= new PopupPageHandler(page.Parent.FindMauiContext());
var androidNativeView = handler.PlatformView as Android.Views.View;
DecoreView?.AddView(androidNativeView);