Xamarin FindViewById返回null [英] Xamarin FindViewById returns null
问题描述
大家好,我需要一点点的建议。我试图用Xamarin让C#做一个Android应用程序。我做了两个布局,并在他们每个人我做牵引按钮them.I之间进行导航试过这样的:
Hi guys I need a little advice. I trying to made 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);
}
}
}
但每次当我启动应用程序,我得到这个errror时间信息:System.NullReferenceException已经thrown.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?
推荐答案
正在设置主
为您的活动的布局,然后在$ C $以下行c您是要求找到一个名为返回
在运行时是不是这个布局的组成部分按钮。这意味着下面一行将返回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&LT;按钮&GT;(Resource.Id.BackButton)。点击
,你一定会得到一个 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屋!