mindvirus
mindvirus

Reputation: 5246

ListView distance from top of the list

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?

Upvotes: 2

Views: 1854

Answers (2)

Phil
Phil

Reputation: 36289

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 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); 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 in distances.

Upvotes: 1

speakingcode
speakingcode

Reputation: 1506

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former 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 both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

In addition, several convenience methods are offered to avoid unnecessary computations, namely getRight() and getBottom(). These methods return the coordinates of the right and bottom edges of the rectangle representing the view. For instance, calling getRight() is similar to the following computation: getLeft() + getWidth() (see Size for more information about the width.)

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

Retrieve the view using getItemAtPosition()

Upvotes: 1

Related Questions