This article describes how to record and restore the scroll position of a listview,Records the coordinates (recommended) and ),Record the position of the first item displayed on the screen by listview,Notifies the adapter of data changes.
Sometimes, when switching a view, you need to restore the position that the listview has previously rolled to. Since existing information on the internet is about the second method, the second method is poor in accuracy, I found the first way to share it.
1. Record the coordinates of the position where the listview is rolled to, and use listview. scrollto to precisely restore
Listview. setonscrolllistener (New onscrolllistener () {/*** call when the rolling status changes */@ override public void onscrollstatechanged (abslistview view, int scrollstate) {// If (scrollstate = onscrolllistener. scroll_state_idle) {If (currentmenuinfo! = NULL) {scrolledx = listview. getscrollx (); scrolledy = listview. getscrolly () ;}}/ *** call during rolling */@ override public void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount ){}});
Called at the recovery location
listView.scrollTo(scrolledX, scrolledY);
2. record the position of the first item displayed on the screen by listview, and thenUse listview. setselectionRestore
This is the most common method that can be found on the Internet, but it cannot be accurately restored to the original position. You can only locate the position of each item. We recommend that you use 1st
Listview. setonscrolllistener (New onscrolllistener () {/*** call when the rolling status changes */@ override public void onscrollstatechanged (abslistview view, int scrollstate) {// If (scrollstate = onscrolllistener. scroll_state_idle) {position = listview. getfirstvisibleposition () ;}}/*** call when rolling */@ override public void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount ){}});
Called at the recovery location
listView.setSelection(position);
Because of the defects in this method, you can use listview. scrollto (x, y) Scrolls to a certain position, such as scrollview. scrollto (0, 0) indicates rolling to the top. This is the first method, so as to implement accurate rolling position recovery.
3. Notify the listview adapter Data Change
This applies to the case where the listview appends data, strictly speaking, it is not to restore the position of the listview scroll, but to keep the scroll position good. But it is the most practical, as long as the listview adapter can be restored without changing.
listDataAdapter.getDataList.addAll(newDataList()); listDataAdapter.notifyDataSetChanged();
Source: http://trinea.iteye.com/blog/1481474