本文介绍了调用notifyDataSetChanged后在ListView中保留位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当用户滚动到底部时,我使用 OnScrollListener 将项目动态添加到 ListView.在我将数据添加到适配器并调用 notifyDataSetChanged 之后,ListView 返回到顶部.理想情况下,我想保留在 ListView 中的位置.关于我应该如何做这件事的任何想法?
I'm using an OnScrollListener to dynamically add items to a ListView when the user scrolls to the bottom. After I add the data to the adapter and call notifyDataSetChanged though, the ListView goes back up to the top. Ideally, I would like to retain the position in the ListView. Any thoughts on how I should go about doing this?
推荐答案
这会是您想要的吗?
// 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:
EDIT 28/09/2017:
API 自 2015 年以来发生了很大变化.它是相似的,但现在是:
The API has changed quite a bit since 2015. It is similar, but now it would be:
// save index and top position
int index = mList.FirstVisiblePosition; //This changed
View v = mList.getChildAt(0);
int top = (v == null) ? 0 : v.Top; //this changed
// notify dataset changed or re-assign adapter here
// restore the position of listview
mList.setSelectionFromTop(index, top);
这篇关于调用notifyDataSetChanged后在ListView中保留位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!