android - 新数据插入后保存RecyclerView中特定项目的位置

标签 android android-recyclerview android-adapter

我实现了RecyclerView,它有两个ViewType。该列表是动态的,当用户向下/向上滚动时,它会添加一些项目。在我的 RecyclerView 中,只有一个项目具有不同的 ViewType (将其视为可扩展列表,一次只有一个项目展开)。

我保存扩展项目的位置但是当添加新数据时此位置发生变化并且我丢失了扩展项目。由于数据是在向下/向上滚动中添加的,因此根据新数据的大小更新扩展项不是一个好主意。

值得一提的是,我想在第一次加载时滚动到展开的项目。所以我想保存位置将是最好的选择。 (我猜,但我不确定);

我想知道处理这个问题的有效方法是什么?

最佳答案

http://tutorials.jenkov.com/java-collections/hashcode-equals.html

实现 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 expanded item
int expandedItemIndex = EmployeeList.indexOf(expandedEmployeeModel);
recyclerView.scrollToPosition(expandedItemIndex);

关于android - 新数据插入后保存RecyclerView中特定项目的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38450846/

相关文章:

java - 如何在单行中绘制具有不同颜色的折线图

android - Firebase 搜索查询不适用于 Android

java - 裁剪后的图像在 android 中模糊

listview - 使用Kotlin的RecyclerView不能垂直放置单元

android - 带有 ToggleButton 过滤器的 ListView 适配器

android - 在 FragmentPagerAdapter 中间插入页面

android - 如何使用 org.jetbrains.anko.startActivity 来优化 startActivity 功能?

android RecyclerView 背景颜色

android-studio - 滚动时选定的图像按钮会更改其在 recyclerView 中的位置

java - 将项目添加到 ListView 适配器中的特定列