Android getting exact scroll position in ListView

前端 未结 8 1242
误落风尘
误落风尘 2020-12-01 02:56

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?

8条回答
  •  悲&欢浪女
    2020-12-01 03:37

    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 listViewItemHeights = new Hashtable();
    
    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;
    }
    

提交回复
热议问题