Android ListView Error with Xamarin



我收到一个未处理的异常错误:"System.NullReferenceException: Object reference Not Set to a object 的实例"时尝试运行以下 Xamarin Android 应用。

using Android.App;
using Android.OS;
using Android.Widget;
using System;
namespace CrossTest1.Droid
{
    [Activity(Label = "CrossTest1.Droid", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : ListActivity
    {
        private int count = 1;
        private BetsViewModel viewModel1;
        private String[] planets = new String[] { "Apple", "Banana", "Mango", "Grapes" };
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);
            viewModel1 = new BetsViewModel();
            Button button = FindViewById<Button>(Resource.Id.myButton);
            ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.listView1, Resource.Id.label, planets);
            ListView listView = (ListView)FindViewById(Resource.Id.listView1);
            listView.SetAdapter(adapter);
            button.Click += delegate
           {
               button.Enabled = false;
               button.Enabled = true;
           };
        }
    }
}

下面是我的 axml 文件。

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button
        android:id="@+id/myButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <ListView
        android:minWidth="25px"
        android:minHeight="25px"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView1" />
   <TextView 
      android:id="@+id/label"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="10dip"
      android:textSize="16dip"
      android:textStyle="bold" />
</LinearLayout>

我假设您在运行时遇到Android膨胀异常:

ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.listView1, Resource.Id.label, planets);

您需要传递项目的布局而不是列表视图:

ArrayAdapter adapter = new ArrayAdapter<String>(this, Resource.Id.YOURLISTVIEWITEMLAYOUT, Resource.Id.label, planets);

最新更新