这里的初级开发人员请好好玩:)
我的应用程序使用RecyclerView显示从服务器返回的项目列表。适配器和刷新工作正常,但更新/刷新列表时应用程序暂时挂起/冻结。
我确信它在遇到NotifyDataSetChanged()时会冻结,因为这会重绘列表中的所有内容(列表中可能有数百个项目)。在线查看之后,看起来DiffUtil可能正是我所追求的,但我找不到任何Xamarin.Android的文档或教程,只是常规的基于Java的Android,我不懂任何语言足以翻译它。
如果有人能指出我正确的方向,我将不胜感激!
在阅读了VideoLAN:https://geoffreymetais.github.io/code/diffutil/的这篇文章之后,我能够让DiffUtil在Xamarin.Android中运行。他解释得非常好,他的项目中的例子非常有用。
下面是我的实现的“通用”版本。我建议在实现你自己的回调之前阅读每个override
调用的内容(参见上面的链接)。相信我,它有所帮助!
回调:
using Android.Support.V7.Util;
using Newtonsoft.Json;
using System.Collections.Generic;
class YourCallback : DiffUtil.Callback
{
private List<YourItem> oldList;
private List<YourItem> newList;
public YourCallback(List<YourItem> oldList, List<YourItem> newList)
{
this.oldList = oldList;
this.newList = newList;
}
public override int OldListSize => oldList.Count;
public override int NewListSize => newList.Count;
public override bool AreItemsTheSame(int oldItemPosition, int newItemPosition)
{
return oldList[oldItemPosition].Id == newList[newItemPosition].Id;
}
public override bool AreContentsTheSame(int oldItemPosition, int newItemPosition)
{
// Using JsonConvert is an easy way to compare the full contents of a data model however, you can check individual components as well
return JsonConvert.SerializeObject(oldList[oldItemPosition]).Equals(JsonConvert.SerializeObject(newList[newItemPosition]));
}
}
而不是调用NotifyDataSetChanged()
执行以下操作:
private List<YourItem> items = new List<YourItem>();
private void AddItems()
{
// Instead of adding new items straight to the main list, create a second list
List<YourItem> newItems = new List<YourItem>();
newItems.AddRange(items);
newItems.Add(newItem);
// Set detectMoves to true for smoother animations
DiffUtil.DiffResult result = DiffUtil.CalculateDiff(new YourCallback(items, newItems), true);
// Overwrite the old data
items.Clear();
items.AddRange(newItems);
// Despatch the updates to your RecyclerAdapter
result.DispatchUpdatesTo(yourRecyclerAdapter);
}
可以通过使用自定义有效负载等来进一步优化它,但这已经超越了在适配器上调用NotifyDataSetChanged()
。
我花了一段时间试图在网上找到的最后几件事:
DispatchUpdatesTo(yourRecyclerAdapter)
的方法不必在您的适配器中,它可以在您的活动或片段中这对我来说也是一个新鲜事,我以前见过这个。我刚刚尝试了它,并在半小时后让它工作。
所以有些来自这里:https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00
基本上它说的是:
List
,IEnumerable
等......)听起来你已经拥有了它,所以这很好。DiffUtil.Callback
类,你将传递旧的和新的数据,这个类将比较一个与另一个。如果您有疑问或遇到问题,请告诉我。