Amir Amir - 4 months ago 51
Android Question

Save position of specific item in RecyclerView after new data insertion

I implement

RecyclerView
which have two
ViewType
. The list is dynamic and when user scroll down/up it add some items. In my
RecyclerView
just one of the item has different
ViewType
(consider this as expandable list which only one of item expand at a time).

I save position for expanded item But when new data added this position changed and I lost expanded item. Because data added in scroll down/up, updating expanded item according to size of new data is not good Idea.

One thing to mention is that I want to scroll to expanded item at first load. so I guess saving position would be best choice. (I guess but I'm not sure);

I want to know what's the efficient way to handle this issue?

Answer

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

Implement hashcode and equals method, using this get the position for the expanded model object.

Example :

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