Xamarin.Android中的DiffUtil

问题描述 投票:2回答:2

这里的初级开发人员请好好玩:)

我的应用程序使用RecyclerView显示从服务器返回的项目列表。适配器和刷新工作正常,但更新/刷新列表时应用程序暂时挂起/冻结。

我确信它在遇到NotifyDataSetChanged()时会冻结,因为这会重绘列表中的所有内容(列表中可能有数百个项目)。在线查看之后,看起来DiffUtil可能正是我所追求的,但我找不到任何Xamarin.Android的文档或教程,只是常规的基于Java的Android,我不懂任何语言足以翻译它。

如果有人能指出我正确的方向,我将不胜感激!

android xamarin android-recyclerview refresh freeze
2个回答
2
投票

在阅读了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()

我花了一段时间试图在网上找到的最后几件事:

  • DiffUtil确实可以在片段中运行
  • DiffUtil可以更新空列表(即不需要预先存在的数据)
  • 动画由系统处理(即您不必自己添加)
  • 调用DispatchUpdatesTo(yourRecyclerAdapter)的方法不必在您的适配器中,它可以在您的活动或片段中

0
投票

这对我来说也是一个新鲜事,我以前见过这个。我刚刚尝试了它,并在半小时后让它工作。

所以有些来自这里:https://medium.com/@iammert/using-diffutil-in-android-recyclerview-bdca8e4fbb00

基本上它说的是:

  1. 你有两个不同的数据结构点(ListIEnumerable等......)听起来你已经拥有了它,所以这很好。
  2. 有一个DiffUtil.Callback类,你将传递旧的和新的数据,这个类将比较一个与另一个。
  3. 有一个方法可以将更新与您的实用程序类一起分派。虽然这篇文章的内容有点不对,因为他没有更新旧数据。但是,如果你这样做,那么它必须像我一样工作。

如果您有疑问或遇到问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.