有时在view切换时,需要恢复listView之前滚动到的位置,常用的三种方法如下:
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
if (currentMenuInfo!=null) {
scrolledX = listView.getScrollX();
scrolledY = listView.getScrollY();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
在恢复位置时调用:
listView.scrollTo(scrolledX, scrolledY);
1、记录listView滚动到的位置的坐标,然后利用listView.scrollTo精确的进行恢复
listView.setOnScrollListener(new OnScrollListener() {@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
if (currentMenuInfo!=null) {
scrolledX = listView.getScrollX();
scrolledY = listView.getScrollY();
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
在恢复位置时调用:
listView.scrollTo(scrolledX, scrolledY);
2、记录listView显示在屏幕上的第一个item的位置,然后利用listView.setSelection恢复
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void
onScrollStateChanged(AbsListView view, int scrollState) {
if
(scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
position =
listView.getFirstVisiblePosition();
}
}
@Override
public void
onScroll(AbsListView view, int firstVisibleItem, int
visibleItemCount, int totalItemCount) {
}
});
在恢复位置时调用:
listView.setSelection(position);
3、通知listView的适配器数据变更
这种适用于listView追加数据的情况,严格说不是恢复listView滚动的位置,只是保持滚动位置不错
listDataAdapter.getDataList.addAll(newDataList());
listDataAdapter.notifyDataSetChanged();