简体   繁体   English

Xamarin FindViewById 返回 null

[英]Xamarin FindViewById returns null

I am trying to make an android app using Xamarin so C#.我正在尝试使用 Xamarin so C# 制作一个 android 应用程序。 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);
        }
    }
}

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.但是每次当我启动应用程序时,我都会得到这个错误:System.NullReferenceException has been throw.Object reference not set to an instance of an object。 Any advice or better idea?有什么建议或更好的主意吗?

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.您将Main设置为您的 Activity 的布局,然后在以下代码行中,您要求在运行时找到一个名为Back的按钮,该按钮不属于此布局。 This means the following line will return null:这意味着以下行将返回 null:

FindViewById<Button>(Resource.Id.BackButton)

Now if you do FindViewById<Button>(Resource.Id.BackButton).Click , you will definitely get a System.NullReferenceException .现在,如果你执行FindViewById<Button>(Resource.Id.BackButton).Click ,你肯定会得到System.NullReferenceException

EDIT:编辑:

In view of the comments, here is what you should do to achieve what you are looking for:鉴于评论,以下是您应该做的事情来实现您的目标:

Create two different activities ( Main1 and Main2 ).创建两个不同的活动( Main1Main2 )。 In Main1 you do: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));
    }

Then in Main2 , you do:然后在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));
    }

Since it just happened to me and almost drove me up the wall, here is yet another way FindViewById can return null and how to fix it.由于它刚刚发生在我身上并且差点把我FindViewById墙,这是FindViewById可以返回null另一种方法以及如何修复它。 Probably not a mistake a more experienced Android developer is likely to make, but still, it might prevent some frustration for someone like me in the future.可能不是更有经验的 Android 开发人员可能犯的错误,但它仍然可以防止像我这样的人在未来感到沮丧。

My situation我的情况

  • My control was in the correct view (not a fragment), the ID was assigned correctly, everything used to work just a couple of days ago when I last worked on the project.我的控件在正确的视图中(不是片段),ID 被正确分配,一切都在几天前我上次参与该项目时正常工作。

  • After building the project, the very first FindViewById call in OnCreate of my main view suddenly returned null when run on a physical device构建项目后,在我的主视图的OnCreate的第一个FindViewById调用在物理设备上运行时突然返回null

  • It turns out I had just run some updates through the Android SDK Manager, which introduced a new Android Version (in this case Android 7) to my system, and my device simply did not have that version installed yet.事实证明,我刚刚通过 Android SDK 管理器运行了一些更新,它为我的系统引入了一个新的 Android 版本(在本例中为 Android 7),而我的设备还没有安装该版本。

The solution解决方案

  • In the properties of my Android project, the "Compile using Android version" drop down was set to "Use Latest Platform", which now was pointing to the newly installed Android 7 -- simply setting it to the version of Android running on my test device (in my case 6) and recompiling fixed the null return value.在我的 Android 项目的属性中,“使用 Android 版本编译”下拉菜单设置为“使用最新平台”,现在指向新安装的 Android 7——只需将其设置为我测试中运行的 Android 版本设备(在我的情况下为 6)并重新编译修复了null返回值。

TL;DR Check that the version of Android you are compiling against is in fact supported by the device you are testing on. TL;DR检查您正在编译的 Android 版本实际上是否受您正在测试的设备支持。

You're getting a NullReferenceException because this code:你得到一个NullReferenceException因为这个代码:

FindViewById<Button>(Resource.Id.BackButton)

returns null .返回null This may be caused by either:这可能是由以下任一原因引起的:

  • 1 - You didn't properly annotate the Button with an android:id attribute, like so: 1 - 您没有使用android:id属性正确注释Button ,如下所示:

     <Button ... android:id="@+id/BackButton"/>

--OR-- - 或者 -

  • 2 - that Button isn't defined on the Main layout and therefore it isn't part of the Activity's current view. 2 - 该 Button 未在Main布局上定义,因此它不是 Activity 当前视图的一部分。 Therefore the FindViewById() method can't find it.因此FindViewById()方法找不到它。 Your intended approach to switch screens isn't supported on Android. Android 不支持您预期的切换屏幕方法。

    Which leads to a longer explanation about the Correct way to "switch screens" on Android: navigating between simple activities这导致了关于在 Android 上“切换屏幕”的正确方法的更长解释: 在简单活动之间导航

Try one of these solutions.尝试这些解决方案之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM