I have a ListView, and I want to make a background that scrolls with the list.
I saw the code for Shelves, which works because all of the items in the GridView are the same height, which is a guarantee that I can’t make. I figure that I can use a similar technique (that is, override dispatchDraw), but I need to know the distance from the top of the ListView for each item – how can I pre-calculate this? The ListView is mostly static and fairly small, so it’s okay if I have to recalculate when adding a new item to the list.
So my question is this: Given a ListView and an List adapter, how can I calculate the distance of each item from the top of the list? That is, item 0 would be 0 pixels from the top, item 20 might be 4032 pixels from the top. Alternately, is there a better way to do what I want to do?
In your adapter, keep a second list of distances that is the same size of your list. Initialize it in your constructor. Then, for each getView() call, you can add the height of the view to the value stored at the previous index of this new list. So for example, say you have
List<Integer> distances. When you callgetView(...)withposition = 0, you setdistances.add(0 + view.getHeight());(once your view has been initialized). And for position 1, you will usedistance.add(distances.get(position-1) + view.getHeight);and so on. Then just have a method for getting the distance for a given view index, which returns the value stored at that index indistances.