Xamarin FindViewById返回null

use*_*246 7 c# android xamarin.android

嗨,大家好,我需要一些建议.我试图使用Xamarin创建一个Android应用程序,所以C#.我制作了两个布局,在每一个布局中我制作了两个按钮来在它们之间导航.我试着这样:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但每当我启动应用程序时,我都会得到这样的错误:System.NullReferenceException已被抛出.对象引用未设置为对象的实例.有什么建议或更好的想法?

Ahm*_*hir 11

您将设置Main为活动的布局,然后在以下代码行中,您要求查找Back在运行时命名的按钮,该按钮不是此布局的一部分.这意味着以下行将返回null:

FindViewById<Button>(Resource.Id.BackButton)
Run Code Online (Sandbox Code Playgroud)

如果你这样做FindViewById<Button>(Resource.Id.BackButton).Click,你一定会得到一个System.NullReferenceException.

编辑:

鉴于评论,您应该采取以下措施来实现您的目标:

创建两个不同的活动(Main1Main2).在Main1你这样做:

    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));
    }
Run Code Online (Sandbox Code Playgroud)

然后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));
    }
Run Code Online (Sandbox Code Playgroud)


Fed*_*gui 1

你得到的是NullReferenceException因为这个代码:

FindViewById<Button>(Resource.Id.BackButton)

返回null。这可能是由以下任一原因引起的:

- 或者 -

  • 2 - 该按钮未在Main布局上定义,因此它不是活动当前视图的一部分。因此该FindViewById()方法找不到它。Android 不支持您想要的切换屏幕的方法。

    这导致了关于Android 上“切换屏幕”的正确方法的更长解释: 在简单活动之间导航

尝试这些解决方案之一。