开发者

Update ArrayAdapter in Android

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()... :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜