How 开发者_开发技巧do you update an ArrayAdapter
without losing the scrolling position?
This is how I currently do it. I create an update method in the ArrayAdapter
subclass which does the following:
public void update(List<MyEntity> entities) {
for (MyEntity entity : entities) {
int position = this.getPosition(entity);
if (position >= 0) {
final MyEntity outdateEntity = this.getItem(position);
this.insert(entity, position);
this.remove(outdateEntity);
} else {
this.insert(entity, 0);
}
}
}
public int getPosition(MyEntity updatedEntity) {
for (int i = 0; i < this.getCount(); i++) {
if (this.getItem(i).getId() == updatedEntity.getId()) {
return i;
}
}
return -1;
}
However, this seems awfully inefficient and error-prone. Is there a better way?
Why do you not extend BaseAdapter
in the first place? There you just have to update your list internally and then call notifyDataSetChanged()
... :-)
精彩评论