这里的初级开发者,所以请玩得好:)
我的应用程序使用RecyclerView来显示从服务器返回的项目列表。适配器和刷新工作正常,然而,应用程序挂起/冻结时,更新/刷新列表。
我确信,当它点击NotifyDataSetChanged()时,它就会结冰,因为这会重新绘制列表中的所有内容(列表中可能有数百个条目)。在网上查看之后,DiffUtil可能正是我想要的,但是我找不到Xamarin.Android的任何文档或教程,只是普通的基于Java的Android,而且我对这两种语言都不太懂。
如果有人能为我指明正确的方向,我将不胜感激!
发布于 2018-09-17 11:38:15
在阅读了DiffUtil:https://geoffreymetais.github.io/code/diffutil/的这篇文章之后,我能够让VideoLAN在https://geoffreymetais.github.io/code/diffutil/中工作。他解释得很好,他的项目中的例子非常有用。
下面是我的实现的“通用”版本。在实现自己的回调之前,我建议阅读每个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)的方法不必在适配器中,它可以在活动或片段中。发布于 2018-08-29 18:31:47
这对我来说也是很新鲜的,我以前也见过。我刚才真的试过了,半个小时后就开始工作了。
所以其中一些来自于这里:https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00
它说的基本上是:
List、IEnumerable等)听起来你已经有了,所以这很好。DiffUtil.Callback类,您将在其中传递旧的和新的数据,该类将比较其中一个数据和另一个数据。如果你有问题或遇到问题请告诉我。
https://stackoverflow.com/questions/52079910
复制相似问题