Why does MainActivity base.OnCreate() fail for Android when a Custom Renderer is enabled with UseMauiCompatibility() in MauiProgram.cs?

dg2k 1,386 Reputation points
2022-08-05T13:15:24.333+00:00

I am migrating Xamarin code to .NET MAUI and I followed @David Ortinau Wiki on Custom Renderers as described here.

The custom renderer is for the Shellcontrol and whenUseMauiCompatibility()is activated in MauiProgram.cs, anInvalidCastExceptionis thrown inMainActivity` as shown below.

Any help is appreciated as to what causes this and any workaround for this issue.

  • .NET MAUI: ver 6.0.486
  • Platform: Android
  • Visual Studio: ver 17.3.0 Preview 6.0

228500-exception.png

UPDATE

I did some inspection of program flow from debugging Call Stack and here is more info:

When rendering is activated, the execution of base.OnCreate(savedInstanceState); in the OnCreate(Bundle savedInstanceState) goes to the renderer constructor (line #3 below). It is on return from initializing the ShellCustomRenderer class that the exception is thrown.

The ShellRenderer is from Microsoft.Maui.Controls.Handlers.Compatibility namespace and I cannot spot where the invalid casting is taking place between hitting base.OnCreate(savedInstanceState); and initializing the renderer class ShellCustomRenderer below.

public class ShellCustomRenderer : ShellRenderer  
{  
    public ShellCustomRenderer(Context context) : base(context)  
    {  

    }  

    protected override IShellToolbarAppearanceTracker CreateToolbarAppearanceTracker()  
    {  
        return new CustomToolbarTracker();   // CustomToolbarTracker class not shown here for brevity  
    }  
}  
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,977 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,386 Reputation points Microsoft Vendor
    2022-08-06T02:55:17.233+00:00

    Hello,​

    If you want to use custom renderer for shell in MAUI, you can register shell handler in MauiProgram.cs like following code

       builder  
       	.UseMauiApp<App>()  
                   .ConfigureMauiHandlers(handlers => {  
       			#if ANDROID  
                       handlers.AddHandler(typeof(Shell), typeof(ShellCustomRenderer));  
       			#endif  
                   })  
    

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful