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:
32
Mopups/Mopups.Maui/Extensions/MauiExtensions.cs
Normal file
32
Mopups/Mopups.Maui/Extensions/MauiExtensions.cs
Normal 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;
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
Reference in New Issue
Block a user