summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Platform.Android/Renderers/GroupedListViewAdapter.cs
blob: 313ded24f3f862de462f812a1764633cbbe01cee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
´╗┐using System;
using System.Collections.Generic;
using System.Linq;
using Android.Content;
using Android.Widget;
using AListView = Android.Widget.ListView;

namespace Xamarin.Forms.Platform.Android
{

	internal class GroupedListViewAdapter : ListViewAdapter, ISectionIndexer
	{
		class SectionData
		{
			public int Index { get; set; }
			public int Length { get; set; }
			public int Start { get; set; }
			public int End => Start + Length;
		}
		public GroupedListViewAdapter(Context context, AListView realListView, ListView listView) : base(context, realListView, listView)
		{

		}
		bool sectionDataValid = false;

		SectionData[] Sections;
		Java.Lang.Object[] nativeSections;
		public int GetPositionForSection(int sectionIndex)
		{
			ValidateSectionData();
			return Sections[sectionIndex].Start;
		}

		public int GetSectionForPosition(int position)
		{
			ValidateSectionData();
			foreach (var section in Sections)
			{
				if (section.Start >= position && section.End <= position)
					return section.Index;
			}
			return 0;
		}

		public Java.Lang.Object[] GetSections()
		{
			ValidateSectionData();
			return nativeSections;
		}

		void ValidateSectionData()
		{
			if (sectionDataValid)
				return;

			var templatedItems = TemplatedItemsView.TemplatedItems;
			int count = 0;

			var sectionData = new List<SectionData>();
			for (var i = 0; i < templatedItems.Count; i++)
			{
				var groupCount = templatedItems.GetGroup(i).Count;
				sectionData.Add(new SectionData { Index = i, Length = groupCount, Start = count });
				count += groupCount;
			}
			Sections = sectionData.ToArray();

			var shortNames = templatedItems.ShortNames;
			if (shortNames != null)
			{
				nativeSections = shortNames.Select(x => new Java.Lang.String(x)).ToArray();
			}
			sectionDataValid = true;
		}

		protected override void InvalidateCount()
		{
			base.InvalidateCount();
			sectionDataValid = false;
		}
	}
}