启动模拟器时出现此错误:
An unhandled exception occured
我试图调用函数
ciao
在各个方面,使用委托(delegate)。有人可以解释为什么这是错误的吗?using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Prova
{
[Activity(Label = "Prova", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
Button saved;
protected override void OnCreate(Bundle bundle)
{
saved = FindViewById<Button>(Resource.Id.Saved);
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
saved.Click += (object sender, EventArgs e) => {
ciao(sender, e);
};
}
private void ciao (object sender, EventArgs e)
{
}
}
}
最佳答案
很难确定问题出在哪里,因为您没有包含完整的异常和堆栈跟踪,但我可以在这里看到会导致代码失败的一件事是您正试图将按钮拉出 UI在您实际设置 View 之前。 FindViewById()
如果无法找到 View ,则返回 null,因此您可能会遇到 NullReferenceException
尝试附加点击处理程序时。
您应该更新您的 OnCreate
方法看起来像这样:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
saved = FindViewById<Button>(Resource.Id.Saved);
saved.Click += ciao;
}
关于android - Xamarin 函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32925504/