【问题标题】:RecyclerView.Adapter notifyItemChanged() with async network update?RecyclerView.Adapter notifyItemChanged() 与异步网络更新?
【发布时间】:2015-03-20 02:11:18
【问题描述】:

我有一个使用 LinearLayoutManager 的 RecyclerView 和一个自定义的 RecyclerView.Adapter。当用户长按一个项目时,它会触发仅该项目的异步网络刷新。我知道长按时项目的位置,我可以将该位置传递给网络刷新功能。但是,当刷新完成并调用notifyItemChanged() 时,用户可能已经添加或删除了一个新项目。因此,虽然刷新的项目可能源自位置 4,但在刷新完成时,它可能位于 3 或 5 或其他位置。

如何确保调用notifyItemChanged() 时使用正确的位置参数?

【问题讨论】:

    标签: android android-viewholder android-recyclerview


    【解决方案1】:

    以下是三种可能的解决方案:

    1. 请致电 notifyDataSetChanged() 并收工。

    2. 通过适配器中的唯一 ID 保留单独的项目地图。让网络刷新返回项目以及唯一 ID。通过 ID 映射访问该项目并确定其位置。显然,如果您的商品没有唯一 ID,则无法选择。

    3. 跟踪正在刷新的项目。注册您自己的AdapterDataObserver 并跟踪所有插入和更新,每次计算项目的新位置并保存直到刷新返回。

    【讨论】:

      【解决方案2】:

      虽然 notifyDataSetChanged() 可以解决问题,但如果必须知道项目的位置,您始终可以在 recyclerview 适配器中使用的列表项目的模型类中实现 hashCode 和 equals。

      实现 hashcode 和 equals 方法来获取所需模型对象的位置。

      例子:

      public class Employee {
          protected long   employeeId;
          protected String firstName;
          protected String lastName;
      
          public boolean equals(Object o){
          if(o == null)                return false;
          if(!(o instanceof) Employee) return false;
      
          Employee other = (Employee) o;
          if(this.employeeId != other.employeeId)      return false;
          if(! this.firstName.equals(other.firstName)) return false;
          if(! this.lastName.equals(other.lastName))   return false;
      
          return true;
        }
      
        public int hashCode(){
          return (int) employeeId;
        }
      }
      
      // To get the index of selected item which triggered async task :
      int itemIndex = EmployeeList.indexOf(selectedEmployeeModel);
      recyclerView.scrollToPosition(itemIndex);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多