Android ListView - 更新时滚动回顶部 [英] Android ListView - scrolls back to top on update
问题描述
我有一个列表视图,可以根据请求添加其他视图,由 BaseAdapter 维护.更新后如何保持滚动位置?
I have a listview that gets additional views added on request, that's maintained by a BaseAdapter. How can I maintain scroll position after the update?
我知道这已经被问过几次了,但每次都提出了同样的解决方案,我试过了,就是在更新后调用adapter.notifyDataSetChanged();
包含列表内容的 ArrayList.
I know this has been asked a few times, but each time, the same solution has been put forward, which I have tried, which is to call adapter.notifyDataSetChanged();
after updating the ArrayList that contains the list contents.
如何确保滚动位置保持不变?
How can I ensure that scroll position is maintained?
推荐答案
在您的活动类中实现一个 OnScrollListener
,然后使用以下代码:
Implement an OnScrollListener
in your activity class and then use the following code:
int currentFirstVisibleItem, currentVisibleItemCount, currentTotalItemCount;
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0
&& this.currentScrollState == SCROLL_STATE_IDLE) {
//Do your work
}
}
}
如果您使用 AsyncTask
来更新您的数据,那么您可以在 PostExecute()
中包含以下内容以保持滚动位置:
If you are using AsyncTask
for updating your data, then you can include the following in your PostExecute()
in order to maintain the Scroll position:
list.setAdapter(adapter);
list.setSelectionFromTop(currentFirstVisibleItem, 0);
我希望这会有所帮助.
这篇关于Android ListView - 更新时滚动回顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!