Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/215.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 插入新数据后在RecyclerView中保存特定项的位置_Android_Android Recyclerview_Android Adapter - Fatal编程技术网

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

Android 插入新数据后在RecyclerView中保存特定项的位置,android,android-recyclerview,android-adapter,Android,Android Recyclerview,Android Adapter,我实现了RecyclerView,它有两个ViewType。列表是动态的,当用户向下/向上滚动时,会添加一些项目。在myRecyclerView中,只有一个项目具有不同的ViewType(将此视为一个可展开列表,一次只展开一个项目) 我保存展开项的位置,但当新数据添加时,此位置发生更改,我丢失展开项。因为在向下/向上滚动中添加了数据,所以根据新数据的大小更新扩展项不是一个好主意 需要提到的一点是,我想在第一次加载时滚动到扩展项。所以我想保住职位是最好的选择。(我猜,但我不确定) 我想知道处理这个

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

我保存展开项的位置,但当新数据添加时,此位置发生更改,我丢失展开项。因为在向下/向上滚动中添加了数据,所以根据新数据的大小更新扩展项不是一个好主意

需要提到的一点是,我想在第一次加载时滚动到扩展项。所以我想保住职位是最好的选择。(我猜,但我不确定)


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

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

重要的是,您对保存的位置使用特殊参照您需要做的是,将(扩展项的)位置放在当前模型中。毕竟大多数都可以正常工作


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

谢谢你的回复。在第一次加载项目时,我想移动到扩展项目,您知道如何执行此操作吗?我使用项目的位置是因为我使用了recyclerview.scrolltoPosition()来解决此问题,但对于您的解决方案,它不再起作用。在您使用的模型类中实现hashcode和equals。使用ArrayList.indexOf(model_对象)获取展开项的位置,对其使用recyclerview.scrolltoPosition()。希望能有帮助@非常感谢你的提示。将其作为解决方案发布:)