2 ways to record and restore listView scroll position:
Record the coordinates of the position where the listView is scrolled (higher accuracy is recommended), record the position of the first item displayed by the listView on the screen (poor accuracy), and notify the adapter of data changes (preserving the listview position when appending data is good).
1. Record the coordinates of the position where the listView is scrolled, and then use listView.scrollTo to restore it accurately:
Record
listView.setOnScrollListener(new OnScrollListener() { // Called when the scroll state changes @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Save the current scrolled position when not scrolling if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { if (currentMenuInfo != null) { scrolledX = listView.getScrollX(); scrolledY = listView.getScrollY(); } } } // called when scrolling @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } });
恢复:listView.scrollTo(scrolledX, scrolledY);
2. Record the position of the first item displayed by the listView on the screen, and then restore it using listView.setSelection :
This is the most common method that can be found on the Internet, but it cannot be restored to the original position accurately. It can only locate the position of each item. It is recommended to use the first method.
Record:
listView.setOnScrollListener(new OnScrollListener() { // Called when the scroll state changes @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Save the current scrolled position when not scrolling if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { position = listView.getFirstVisiblePosition(); } } // called when scrolling @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } });
Restore: listView.setSelection(position);
3. Notify the adapter data change of listView
This applies to the case of appending data to the listView. Strictly speaking, it is not to restore the scrolling position of the listView, but to maintain the scrolling position.
listDataAdapter.getDataList.addAll (newDataList ()); listDataAdapter.notifyDataSetChanged();