Xamarin FindViewById 返回 null [英] Xamarin FindViewById returns null
问题描述
我正在尝试使用 Xamarin so C# 制作一个 android 应用程序.我做了两个布局,在每个布局中我都做了两个按钮来在它们之间导航.我试过这样:
I am trying to make an android app using Xamarin so C#. I made two layouts and in each one of them I made tow buttons to navigate between them.I tried like this:
using System;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
namespace Example
{
[Activity(Label = "Example", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.Main);
this.FindViewById<Button>(Resource.Id.ForwardButton).Click += this.Forward;
this.FindViewById<Button>(Resource.Id.BackButton).Click += this.Back;
}
public void Forward(object sender, EventArgs e)
{
this.SetContentView(Resource.Layout.Main2);
}
public void Back(object sender, EventArgs e)
{
this.SetContentView(Resource.Layout.Main);
}
}
}
但是每次当我启动应用程序时,我都会得到这个错误:System.NullReferenceException has been throw.Object reference not set to an instance of an object.有什么建议或更好的主意吗?
But every time when I start the app I get this errror: System.NullReferenceException has been thrown.Object reference not set to an instance of an object. Any advice or better idea?
推荐答案
您正在将 Main
设置为您的活动的布局,然后在以下代码行中您要求找到一个名为的按钮Back
在运行时不属于此布局的一部分.这意味着以下行将返回 null:
You are setting Main
as the layout for your activity and then in the following lines of code you are asking to find a button named Back
at runtime which is not part of this layout. This means the following line will return null:
FindViewById<Button>(Resource.Id.BackButton)
现在如果你执行FindViewById
,你肯定会得到一个System.NullReferenceException
.
Now if you do FindViewById<Button>(Resource.Id.BackButton).Click
, you will definitely get a System.NullReferenceException
.
鉴于评论,以下是您应该做的事情以实现您的目标:
In view of the comments, here is what you should do to achieve what you are looking for:
创建两个不同的活动(Main1
和 Main2
).在 Main1
中:
Create two different activities (Main1
and Main2
). In Main1
you do:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.Main);
this.FindViewById<Button>(Resource.Id.ForwardButton).Click += this.Forward;
}
public void Forward(object sender, EventArgs e)
{
this.StartActivity (typeof(Main2));
}
然后在 Main2
中:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
this.SetContentView(Resource.Layout.Main2);
this.FindViewById<Button>(Resource.Id.BackButton).Click += this.Back;
}
public void Back(object sender, EventArgs e)
{
this.StartActivity (typeof(Main));
}
这篇关于Xamarin FindViewById 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!