为什么TextView会抛出此错误?

时间:2014-04-21 10:14:20

标签: android xamarin.android xamarin baseadapter

以下代码用于在Xamarin中使用BaseAdapter填充列表。 问题是,在GetView()函数中,当我更改TextView的文本时,它会抛出

Object Reference not set to an instance of an object

异常。屏幕截图附有详细信息...... Object Reference not set to an instance of an object

以下代码是.axml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/dialogContainer"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFF"
    android:paddingBottom="25dip">
    <TextView
        android:id="@+id/contact"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Default Contact" />
</RelativeLayout>

以下代码为GetView()函数:

public override View GetView (int position, View convertView, ViewGroup parent)
{
    View view = convertView ?? _Context.LayoutInflater.Inflate(Resource.Layout.SelectContactsItem, parent, false);

    var textView = _Context.FindViewById<TextView> (Resource.Id.contact);
    Console.WriteLine (_ContactList.ElementAt(position).Name);
    textView.Text = _ContactList.ElementAt (position).Name;
    return view;
}

2 个答案:

答案 0 :(得分:3)

不确定xamarin语法但是......你可能在这里做错了。

 var textView = _Context.FindViewById<TextView> (Resource.Id.contact);
                ^^^^^^^^

用......替换此行

 var textView = view.FindViewById<TextView> (Resource.Id.contact);

Rererence Link

答案 1 :(得分:0)

尝试更改

public override View GetView (int position, View convertView, ViewGroup parent)
{
    View view = convertView ?? _Context.LayoutInflater.Inflate(Resource.Layout.SelectContactsItem, parent, false);

    var textView = _Context.FindViewById<TextView> (Resource.Id.contact);
    Console.WriteLine (_ContactList.ElementAt(position).Name);
    textView.Text = _ContactList.ElementAt (position).Name;
    return view;
}

用这个

public override View GetView (int position, View convertView, ViewGroup parent)
{
    View view = convertView ?? _Context.LayoutInflater.Inflate(Resource.Layout.SelectContactsItem, parent, false);

    var textView = view.FindViewById<TextView> (Resource.Id.contact);
    Console.WriteLine (_ContactList.ElementAt(position).Name);
    textView.Text = _ContactList.ElementAt (position).Name;
    return view;
}