Three ways to record and restore the location of the ListView scroll
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 (New Onscrolllistener () {/** * * When the scrolling state is changed */@Overridepublic void onscrollstatechanged ( Abslistview view, int scrollstate) {///do not scroll when saving the current scroll to the position if (scrollstate = = Onscrolllistener.scroll_state_idle) {if ( Currentmenuinfo = null) {Scrolledx = Listview.getscrollx (); scrolledy = Listview.getscrolly ();}}} /** * When scrolling * * * @Overridepublic void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcou NT) {}});
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 (New Onscrolllistener () {/** * * When the scrolling state is changed */@Overridepublic void onscrollstatechanged ( Abslistview view, int scrollstate) {///do not scroll when saving the current scroll to the position if (scrollstate = = Onscrolllistener.scroll_state_idle) {position = L Istview.getfirstvisibleposition ();}} /** * When scrolling * * * @Overridepublic void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcou NT) {}});
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