在 Xamarin 中导航原生表单会导致空引用异常

unc*_*oge 5 c# xamarin.android xamarin xamarin.forms

我在 Xamarin.Android 项目(本机)中有 4 个选项卡。本机加载了 3 个选项卡,但我加载的一个选项卡是表单页面(内容页面)。这是选项卡的代码-

    public override Android.Support.V4.App.Fragment GetItem(int position)
        {

            switch (position)
            {
                case 0:
                    return new tab1Fragment();

                case 1:
                    return new tab2Fragment();

                case 2:
                    return new tab3Fragment();                   

                case 3:
                   var fragment = new FormsPage1().CreateSupportFragment(Android.App.Application.Context);
                    return fragment;

                default:
                    return null;
            }
        }
Run Code Online (Sandbox Code Playgroud)

表单页面已成功加载,但是当我触摸该页面中的任何位置时,它会崩溃。这是例外情况-

System.NullReferenceException: Object reference not set to an instance of an object.
at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_e)
  at (wrapper dynamic-method) System.Object.55(intptr,intptr,intptr)
 Unhandled Exception from source=AndroidEnvironment
 System.NullReferenceException: Object reference not set to an instance of an object.
  at Xamarin.Forms.Platform.Android.PlatformRenderer.DispatchTouchEvent (Android.Views.MotionEvent e) 
at Android.Views.View.n_DispatchTouchEvent_Landroid_view_MotionEvent_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_e)
Run Code Online (Sandbox Code Playgroud)

更新 Xaml-

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:ClientApp"
         x:Class="ClientApp.FormsPage1">

<StackLayout>
    <!-- Place new controls here -->
    <Label Text="Welcome to Xamarin.Forms!" 
       HorizontalOptions="Center"
       VerticalOptions="CenterAndExpand" />
</StackLayout>
Run Code Online (Sandbox Code Playgroud)

当我调试更多片段的视图始终为空时,我怀疑这是导致问题的原因,但不确定..请帮助..

Iva*_*čin 5

我希望这个问题会出现,因为您使用的是应用程序Context而不是活动Context。在大多数情况下,它作为上下文提供者很好,但有时会导致问题。

我不确定您的项目结构是否推荐了如何获取活动上下文的最佳解决方案,但 CurrentActivity 插件应该适用于所有情况。