سؤال

The following code is for populating a list using BaseAdapter in Xamarin. The problem is, in GetView() function when I change the text of TextView, it throws the

Object Reference not set to an instance of an object

exception. Screenshot is attached for detail ... Object Reference not set to an instance of an object

Following code is .axml file

<?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>

And this following code is of GetView() function:

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;
}
هل كانت مفيدة؟

المحلول

Not sure about xamarin syntax but...you may doing something wrong here.

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

replace this line with...

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

Rererence Link

نصائح أخرى

Try to change

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;
}

with this

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top