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

Save position of specific item in RecyclerView after new data insertion

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

我保存扩展项的位置但是当添加新数据时这个位置改变了,我丢失了扩展项。因为在 scroll down/up 中添加了数据,所以根据新数据的大小更新扩展项不是一个好主意。

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

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

您可能使用模型将数据加载到 RecyclerView。此模型(例如 ContactModel)包含您的 ViewHolder 的不同值。

重要的是,您对保存的位置使用特殊引用。 您需要做的,就是将(扩展项的)位置放到当前模型中。毕竟大部分工作正常。

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);