I have 4 tabs in Xamarin.Android project(natively). 3 tabs are loaded natively,but one tab I am loading is a Forms page(content page). Here is the codes for tabs-
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;
}
}
The forms page is loaded successfully,but when I touch anywhere in that page,it crashes.Here is the exception-
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)
Updating the 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>
When I debugged more the view of the fragment always null,I am suspecting that this is causing the issue, but not sure..Please help ..
I would expect this problem to appear because you are using the app's Context
and not the activity Context
. In most cases it is fine as a context provider, but sometimes it causes problems.
I am not sure of your project structure to recommend the best solution of how to get the activity context, but the CurrentActivity plugin should work in all cases.
user Xamarin.Forms.Forms.Init(this, null); in your code before you create fragment
if (__fragment1 == null)
{
// iOS
//Forms.Init()
//var iosViewController = new MyFormsPage().CreateViewController();
Xamarin.Forms.Forms.Init(this, null);
// #2 Use it
_fragment1 = new MainPage().CreateFragment(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With