Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android getting exact scroll position in ListView

I'd like to get the exact, pixel position of the ListView scroll. And no, I am not referring to the first visible position.

Is there a way to achieve this?

like image 965
saarraz1 Avatar asked May 30 '12 00:05

saarraz1


People also ask

How to get scroll position in ListView Android?

Okay, I found a workaround, using the following code: View c = listview. getChildAt(0); int scrolly = -c.

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

During page unload, get the scroll position and store it in local storage. Then during page load, check local storage and set that scroll position.

How do I listen to scroll position in flutter?

I used NotificationListener that is a widget that listens for notifications bubbling up the tree. Then use ScrollEndNotification , which indicates that scrolling has stopped. For scroll position I used _scrollController that type is ScrollController .


2 Answers

Okay, I found a workaround, using the following code:

View c = listview.getChildAt(0); int scrolly = -c.getTop() + listview.getFirstVisiblePosition() * c.getHeight(); 

The way it works is it takes the actual offset of the first visible list item and calculates how far it is from the top of the view to determine how much we are "scrolled into" the view, so now that we know that we can calculate the rest using the regular getFirstVisiblePosition method.

like image 189
saarraz1 Avatar answered Oct 14 '22 18:10

saarraz1


Saarraz1's answer will only work if all the rows in the listview are of the same height and there's no header (or it is also the same height as the rows).

Note that once the rows disappear at the top of the screen you don't have access to them, as in you won't be able to keep track of their height. This is why you need to save those heights (or accumulated heights of all). My solution requires keeping a Dictionary of heights per index (it is assumed that when the list is displayed the first time it is scrolled to the top).

private Dictionary<Integer, Integer> listViewItemHeights = new Hashtable<Integer, Integer>();  private int getScroll() {     View c = listView.getChildAt(0); //this is the first visible row     int scrollY = -c.getTop();     listViewItemHeights.put(listView.getFirstVisiblePosition(), c.getHeight());     for (int i = 0; i < listView.getFirstVisiblePosition(); ++i) {         if (listViewItemHeights.get(i) != null) // (this is a sanity check)             scrollY += listViewItemHeights.get(i); //add all heights of the views that are gone     }     return scrollY; } 
like image 24
Maria Avatar answered Oct 14 '22 16:10

Maria