ListView distance from the top of the list

I have a ListView and I want to create a background that scrolls with a list.

I saw Shelves code that works because all the elements in the GridView are the same height, which is a guarantee that I cannot do it. I suppose I can use a similar method (that is, override dispatchDraw), but I need to know the distance from the top of the ListView for each item - how can I pre-compute it? The ListView is mostly static and quite small, so it’s good if I have to recount when adding a new item to the list.

So my question is this: given that ListView and List adapter, how can I calculate the distance of each item at the top of the list? That is, element 0 will be 0 pixels from above, element 20 may be 4032 pixels from above. Alternatively, is there a better way to do what I want to do?

+2
source share
2 answers

In your adapter, save a second distance list, the size of which is the same as your list. Initialize it in your constructor. Then for each call to getView (), you can add the height of the view to the value stored in the previous index of this new list. For example, let's say you have List<Integer> distances . When you call getView(...) with position = 0 , you set distances.add(0 + view.getHeight()); (once your view has been initialized). And for position 1 you will use distance.add(distances.get(position-1) + view.getHeight); etc. Then just get a method to get the distance for a given view index, which returns the value stored in that index in distances .

+1
source

You can get the location of the view by calling the getLeft () and getTop () methods. The first returns the left or X coordinate of the rectangle representing the view. The latter returns the top or Y, coordinate of the rectangle representing the view. These methods return the location of the view relative to its Parent. For example, when getLeft () returns 20, this means that the view is located 20 pixels to the right of the left edge of its direct ancestor.

In addition, several convenient methods are suggested to avoid unnecessary calculations, namely getRight () and getBottom (). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For example, calling getRight () is similar to the following calculation: getLeft () + getWidth () (see Size for more information on width.)

http://developer.android.com/reference/android/view/View.html

Get view using getItemAtPosition ()

+1
source

All Articles