This article mainly introduces 3 ways to record and restore the ListView scroll position, record the coordinates of where the ListView is scrolled (recommended), record the location of the first item that the ListView displays on the screen, Notifies the adapter of data changes.
Sometimes in view switching, you need to restore the ListView before scrolling to the location, in view of the information on the Internet is the second method, and the second method itself in the accuracy of poor, they found the first method of sharing.
1, record the location of the ListView scroll to the coordinates, and then use Listview.scrollto accurate recovery
Listview.setonscrolllistener (NewOnscrolllistener () {/*** Called when the scrolling state changes*/@Override Public voidOnscrollstatechanged (Abslistview view,intscrollstate) { //Save current Scroll to position without scrolling if(Scrollstate = =onscrolllistener.scroll_state_idle) { if(Currentmenuinfo! =NULL) {Scrolledx=Statuslistview.getscrollx (); Scrolledy=statuslistview.getscrolly (); } } } /*** Called when scrolling*/@Override Public voidOnscroll (Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) { } });
Called when the location is restored
Listview.scrollto (Scrolledx, scrolledy);
2. Record the location of the first item that the ListView displays on the screen, and then using Listview.setselection Recovery
This is the most common way that can be found online, but can not be accurately restored to the original location, can only navigate to the location of each item, recommended the use of the 1th
Listview.setonscrolllistener (NewOnscrolllistener () {/*** Called when the scrolling state changes*/@Override Public voidOnscrollstatechanged (Abslistview view,intscrollstate) { //Save current Scroll to position without scrolling if(Scrollstate = =onscrolllistener.scroll_state_idle) {Position=statuslistview.getfirstvisibleposition (); } } /*** Called when scrolling*/@Override Public voidOnscroll (Abslistview view,intFirstvisibleitem,intVisibleItemCount,intTotalitemcount) { } });
Called when the location is restored
Listview.setselection (position);
Due to the flaw in this way plus the ability to scroll to a location using Listview.scrollto (x, y), such as Scrollview.scrollto (0, 0) means scrolling to the top this reminds me of the first way to achieve accurate scroll position recovery
3. Notify the ListView of adapter data changes
This applies to the ListView append data case, strictly speaking not to restore the ListView scroll position, just keep scrolling position good
ListDataAdapter.getDataList.addAll (Newdatalist ()); Listdataadapter.notifydatasetchanged ();
Three ways to record and restore the location of the ListView scroll