Lew*_*ett 4 android refresh freeze xamarin android-recyclerview
这里的初级开发人员所以请玩得开心:)
我的应用程序使用 RecyclerView 来显示从服务器返回的项目列表。适配器和刷新工作正常,但是,应用程序在更新/刷新列表时会暂时挂起/冻结。
我确信当它点击 NotifyDataSetChanged() 时它会冻结,因为这会重绘列表中的所有内容(列表中可能有数百个项目)。在网上查看后,似乎 DiffUtil 可能正是我所追求的,但我找不到 Xamarin.Android 的任何文档或教程,只是基于 Java 的常规 Android,我对任何一种语言的理解都不足以翻译它。
如果有人能指出我正确的方向,将不胜感激!
从 VideoLAN 阅读这篇文章后,我能够让 DiffUtil 在 Xamarin.Android 中工作: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]));
}
}
Run Code Online (Sandbox Code Playgroud)
而不是调用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);
}
Run Code Online (Sandbox Code Playgroud)
可以通过使用自定义有效负载等来进一步优化它,但这已经是调用NotifyDataSetChanged()适配器的首要任务。
我花了一段时间试图在网上找到的最后几件事:
DispatchUpdatesTo(yourRecyclerAdapter)不必在您的适配器中,它可以在您的活动或片段中| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |