Amir
Amir

Reputation: 16597

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?

Upvotes: 2

Views: 669

Answers (2)

Alok Omkar
Alok Omkar

Reputation: 628

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

Upvotes: 1

GensaGames
GensaGames

Reputation: 5788

Likely you use model for loading data to RecyclerView. And this model (for ex. ContactModel) contains different values for your ViewHolders.

What is point, that you use special references for that saved position. What you need to do, it's just put that position (of expanded item) to current model. And after all most works fine.

Upvotes: 1

Related Questions