com.alicizax.unity.ui.exten.../Runtime/RecyclerView/Adapter/GroupAdapter.cs
陈思海 f22a4f1efa RecyclerView优化
1.分离逻辑视图与渲染视图
2.xxxx若干项懒得写了
2026-03-27 18:38:29 +08:00

123 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
namespace AlicizaX.UI
{
public class GroupAdapter<TData> : Adapter<TData> where TData : IGroupViewData, new()
{
private readonly List<TData> showList = new();
private readonly string groupViewName;
public GroupAdapter(RecyclerView recyclerView, string groupViewName) : base(recyclerView)
{
this.groupViewName = groupViewName;
}
public GroupAdapter(RecyclerView recyclerView, List<TData> list) : base(recyclerView, list)
{
}
public GroupAdapter(RecyclerView recyclerView) : base(recyclerView)
{
}
public override int GetItemCount()
{
return showList.Count;
}
public override string GetViewName(int index)
{
return showList[index].TemplateName;
}
public override void NotifyDataChanged()
{
foreach (var data in list)
{
CreateGroup(data.Type);
}
var groupList = showList.FindAll(data => data.TemplateName == groupViewName);
for (int i = 0; i < groupList.Count; i++)
{
int index = showList.IndexOf(groupList[i]);
Collapse(index);
if (groupList[i].Expanded)
{
Expand(index);
}
}
foreach (var group in groupList)
{
if (list.FindAll(data => data.Type == group.Type).Count == 0)
{
showList.Remove(group);
}
}
base.NotifyDataChanged();
}
public override void SetList(List<TData> list)
{
showList.Clear();
base.SetList(list);
}
private void CreateGroup(int type)
{
var groupData = showList.Find(data => data.Type == type && data.TemplateName == groupViewName);
if (groupData == null)
{
groupData = new TData
{
TemplateName = groupViewName,
Type = type
};
showList.Add(groupData);
}
}
public void Expand(int index)
{
var expandList = list.FindAll(data => data.Type == showList[index].Type);
showList.InsertRange(index + 1, expandList);
}
public void Collapse(int index)
{
var collapseList = showList.FindAll(data => data.Type == showList[index].Type && data.TemplateName != groupViewName);
showList.RemoveRange(index + 1, collapseList.Count);
}
protected override bool TryGetBindData(int index, out TData data)
{
if (index < 0 || index >= showList.Count)
{
data = default;
return false;
}
data = showList[index];
return true;
}
protected override Action CreateItemClickAction(int index, TData data)
{
return () =>
{
if (data.TemplateName == groupViewName)
{
data.Expanded = !data.Expanded;
NotifyDataChanged();
return;
}
SetChoiceIndex(index);
};
}
}
}