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?
Okay, I found a workaround, using the following code: View c = listview. getChildAt(0); int scrolly = -c.
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.
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 .
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With