Xamarin FindViewById 返回 null [英] Xamarin FindViewById returns null

查看:28
本文介绍了Xamarin FindViewById 返回 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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆