Do/can I add ListView section headers in the GetView method?

430 Views Asked by At

In Xamarin, I have a ListView adapter with the following GetView method:

public override View GetView(int position, View convertView, ViewGroup parent)
{
    var item = items[position];
    View view = convertView;
    if (view == null)
        view = context.LayoutInflater.Inflate(Resource.Layout.MapLocationDetail, null);
    view.FindViewById<TextView>(Resource.Id.TextViewMapHeading).Text = item.Heading;
    view.FindViewById<TextView> (Resource.Id.TextViewDescription).Text = item.SubHeading;
    view.FindViewById<ImageView>(Resource.Id.Image).SetImageResource(item.ImageResourceId);
    return view;
}

What is the process to add a default ListView section header at desired positions in the ListView?

Is this done in the GetView method, or somewhere else? Also, is there an inbuilt layout to use for the default section headers?

Thanks in advance

1

There are 1 best solutions below

0
On

Unlike Xamarin.iOS there isn't a handy method you can override for a section header.

What you have to do instead is include your section view in your regular view cell. By default you want to set this section view's visibility to "gone." In your GetView method you can detect if you are at the beginning of the section. If so, you set the visibility of that section view to "visible" and set whatever text that you want.

Here's a small code sample:

var headerTextView = view.FindViewById (Resource.Id.parentDirectoryHeader) as TextView;

if (position != 0) {
    view.FindViewById (Resource.Id.parentDirectoryHeader).Visibility = ViewStates.Visible;
} else {
    view.FindViewById (Resource.Id.parentDirectoryHeader).Visibility = ViewStates.Gone;
}