Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maintain/Save/Restore scroll position when returning to a ListView

I have a long ListView that the user can scroll around before returning to the previous screen. When the user opens this ListView again, I want the list to be scrolled to the same point that it was previously. Any ideas on how to achieve this?

like image 332
rantravee Avatar asked Jun 10 '10 11:06

rantravee


People also ask

How to save and restore the scroll position and state of a android ListView?

getTop() - mList. getPaddingTop() returns its relative offset from the top of the ListView . Then, to restore the ListView 's scroll position, we call ListView. setSelectionFromTop() with the index of the item we want and an offset to position its top edge from the top of the ListView .

How can I retain the scroll position of a scrollable area when pressing back button?

store the position in cookies and after that use the cookie to scroll the page to exact position .

Is ListView scrollable by default?

scrollable Boolean|String (default: false) If set to true the listview will display a scrollbar when the content exceeds the listview height value. By default scrolling is disabled. It could be also set to endless in order to enable the endless scrolling functionality.

Does ListView have scroll?

A ListView in Android is a scrollable list used to display items.


1 Answers

Try this:

// save index and top position int index = mList.getFirstVisiblePosition(); View v = mList.getChildAt(0); int top = (v == null) ? 0 : (v.getTop() - mList.getPaddingTop());  // ...  // restore index and position mList.setSelectionFromTop(index, top); 

Explanation:

ListView.getFirstVisiblePosition() returns the top visible list item. But this item may be partially scrolled out of view, and if you want to restore the exact scroll position of the list you need to get this offset. So ListView.getChildAt(0) returns the View for the top list item, and then View.getTop() - mList.getPaddingTop() returns its relative offset from the top of the ListView. Then, to restore the ListView's scroll position, we call ListView.setSelectionFromTop() with the index of the item we want and an offset to position its top edge from the top of the ListView.

like image 76
ian Avatar answered Sep 21 '22 16:09

ian