android-调用notifyDataSetChanged之后在ListView中保留位置
当用户滚动到底部时,我正在使用OnScrollListener将项目动态添加到ListView。 在将数据添加到适配器并尽管调用了notifyDataSetChanged之后,ListView回到顶部。 理想情况下,我想保留在ListView中的位置。 关于我应该如何做的任何想法?
SeanPONeil asked 2020-08-11T23:08:24Z
7个解决方案
97 votes
这可能是您想要的吗?
// save index and top position
int index = mList.getFirstVisiblePosition();
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
// notify dataset changed or re-assign adapter here
// restore the position of listview
mList.setSelectionFromTop(index, top);
编辑28/09/2017:
自2015年以来,API发生了很大变化。类似,但现在是:
// save index and top position
int index = mList.FirstVisiblePosition; //This changed
View v = mList.getChildAt(0);
int top = (v ==