在我使用Xamarin.forms开发的android应用程序中,每当我更改设备方向时,都会收到NullReferenceException异常,并且该应用程序在Android 9中崩溃。但是在以前的android版本中,该应用程序运行良好。没有崩溃。
这是MainActivity.cs
namespace RSMapp.Droid
{
[Activity(Label = "FIRE", Icon = "@drawable/launcherIcon", Theme = "@style/splashscreen", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation, ScreenOrientation = ScreenOrientation.Portrait)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
internal static MainActivity Instance { get; private set; }
protected async override void OnCreate(Bundle savedInstanceState)
{
TryToGetPermissions();
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.Window.RequestFeature(WindowFeatures.ActionBar);
base.SetTheme(Resource.Style.MainTheme);
UserDialogs.Init(this);
base.OnCreate(savedInstanceState);
Instance = this;
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
CrossCurrentActivity.Current.Init(this, savedInstanceState);
Plugin.InputKit.Platforms.Droid.Config.Init(this, savedInstanceState);
UltimateXFSettup.Initialize(this);
LoadApplication(new App());
}
}
}
我尝试删除ScreenOrientation = ScreenOrientation.Portrait,但是存在问题。
将方向肖像更改为横向后,在“输出”窗口中获取此信息
10-18 11:52:37.366 I/MultiWindowDecorSupport(19021): updateCaptionType >> DecorView@3acb272[MainActivity], isFloating: false, isApplication: true, hasWindowDecorCaption: false, hasWindowControllerCallback: true
10-18 11:52:37.366 D/MultiWindowDecorSupport(19021): setCaptionType = 0, DecorView = DecorView@3acb272[MainActivity]
10-18 11:52:37.373 D/ViewRootImpl@403bf69[MainActivity](19021): MSG_RESIZED_REPORT: frame=[0,0][2048,1536] ci=[0,48][0,0] vi=[0,48][0,0] or=2
10-18 11:52:37.399 D/ViewRootImpl@403bf69[MainActivity](19021): Relayout returned: old=[0,0][2048,1536] new=[0,0][2048,1536] result=0x23 surface={true 490213163008} changed=false
10-18 11:52:37.401 D/OpenGLRenderer(19021): eglDestroySurface = 0x7222da2700, 0x7222fb4000
10-18 11:52:37.402 D/OpenGLRenderer(19021): eglCreateWindowSurface = 0x7222da2700, 0x7222fb4010
Unhandled Exception:
System.NullReferenceException: Object reference not set to an instance of an object.
此代码中存在问题。
public override Resources Resources
{
get
{
if ((int)Build.VERSION.SdkInt >= 25)
{
Configuration config = new Configuration();
config.SetToDefaults();
Context context = CreateConfigurationContext(config);
Resources resources = context.Resources;
return resources;
}
else
{
Resources res = base.Resources;
Configuration config = new Configuration();
config.SetToDefaults();
res.UpdateConfiguration(config, res.DisplayMetrics);
return res;
}
}
}
我正在使用它来省略用户更改为应用程序的系统级字体大小。这给出了Android 9中的错误
ScreenOrientation = ScreenOrientation.Portrait
然后将其添加到您的MainActivity
中:
public override void OnConfigurationChanged(Configuration newConfig)
{
base.OnConfigurationChanged(newConfig);
}