This article mainly introduces 3 ways to record and restore the scroll position of the ListView.record the coordinates of the location where the ListView is scrolled (recommended),records 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 () {
- /**
- * Called when the scrolling state changes
- */
- @Override
- Public void onscrollstatechanged (abslistview view, int scrollstate) {
- Save current Scroll to position when not scrolling
- if (scrollstate = = Onscrolllistener.scroll_state_idle) {
- if (currentmenuinfo! = null) {
- Scrolledx = Statuslistview.getscrollx ();
- Scrolledy = statuslistview.getscrolly ();
- }
- }
- }
- /**
- * Called when scrolling
- */
- @Override
- Public void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {
- }
- });
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 () {
- /**
- * Called when the scrolling state changes
- */
- @Override
- Public void onscrollstatechanged (abslistview view, int scrollstate) {
- Save current Scroll to position when not scrolling
- if (scrollstate = = Onscrolllistener.scroll_state_idle) {
- Position = Statuslistview.getfirstvisibleposition ();
- }
- }
- /**
- * Called when scrolling
- */
- @Override
- Public void onscroll (abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {
- }
- });
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