问题
In my app I replaced AndroidActivity with FormsAppCompatActivity.
Now in a custom renderer extending NavigationRenderer, I get an exception that's traced to method Xamarin.Forms.Platform.Android.NavigationRenderer.SwitchContentAsync:
[MonoDroid] UNHANDLED EXCEPTION:
[MonoDroid] System.InvalidCastException: Cannot cast from source type to destination type.
[MonoDroid] at Xamarin.Forms.Platform.Android.NavigationRenderer.SwitchContentAsync (Xamarin.Forms.Page,bool,bool) <IL 0x000bd, 0x003fe>
[MonoDroid] at Xamarin.Forms.Platform.Android.NavigationRenderer.OnPushAsync (Xamarin.Forms.Page,bool) <IL 0x00004, 0x0003f>
[MonoDroid] at Xamarin.Forms.Platform.Android.NavigationRenderer.PushViewAsync (Xamarin.Forms.Page,bool) <IL 0x00003, 0x00036>
[MonoDroid] at Xamarin.Forms.Platform.Android.NavigationRenderer.<OnElementChanged>b__4_0 (Xamarin.Forms.Page) <IL 0x00003, 0x00033>
[MonoDroid] at Xamarin.Forms.EnumerableExtensions.ForEach<Xamarin.Forms.Page> (System.Collections.Generic.IEnumerable`1<Xamarin.Forms.Page>,System.Action`1<Xamarin.Forms.Page>) <0x000bf>
[MonoDroid] at Xamarin.Forms.Platform.Android.NavigationRenderer.OnElementChanged (Xamarin.Forms.Platform.Android.ElementChangedEventArgs`1<Xamarin.Forms.NavigationPage>) <IL 0x000ea, 0x006ff>
[MonoDroid] at Boats.Droid.PageFancyRenderer.OnElementChanged (Xamarin.Forms.Platform.Android.ElementChangedEventArgs`1<Xamarin.Forms.NavigationPage>) [0x00001] in d:\Code\Boats\Droid\Renderers\NavigationPageFancy.cs:33
I cannot step into it since I don't have the source for Xamarin.Forms. The decompilation of that method is here
Any ideas?
回答1:
This is because AppCompat introduces a new NavigationRenderer, so I should be subclassing that instead of the one in Xamarin.Forms.Platform.Android.
So, the solution is to do:
public class PageFancyRenderer : Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer
instead of:
public class PageFancyRenderer : Xamarin.Forms.Platform.Android.NavigationPageRenderer
Why this error was happening:
Inside NavigationPageRenderer.SwitchContentAsync there is this line:
((Platform) this.Element.Platform).NavAnimationInProgress = false;
Which is doing a cast to Android.Platform class since I was subclassing Android.NavigationRenderer
The correct renderer Android.AppCompat.NavigationRenderer would be casting to the correct platform of the element (when using AppCompatActivity) which is Android.AppCompat.Platform
If Xamarin.Forms was open-souce, this would have been easier to catch because I would be able to actually debug the code, but instead, I had to look at the IL disassembly to find the line that was causing the error.
Please open-source Xamarin.Forms for the sake of the community
来源:https://stackoverflow.com/questions/33318416/migrating-to-formsapplicationactivity-causing-exceptions-in-navigationrenderer