tags:

views:

4059

answers:

3

I need to find out the pixel position of one element in a list that's been displayed using a ListView. It seems like I should get one of the TextViews and then use getTop, but I can't figure out how to get a child view of a ListView.

Thanks!

Update: The children of the ViewGroup do not correspond 1-to-1 with the items in the list, for a ListView. Instead, the ViewGroup's children correspond to only those views that are visible right now. So getChildAt operates on an index that's internal to the ViewGroup and doesn't necessarily have anything to do with the position in the list that the ListView uses. :-/

A: 

A quick search of the docs for the ListView class has turned up getChildCount() and getChildAt() methods inherited from ViewGroup. Can you iterate through them using these? I'm not sure but it's worth a try.

Found it here

Feet
A: 

This assumes you know the position of the element in the ListView :

  View element = listView.getListAdapter().getView(position, null, null);

Then you should be able to call getLeft() and getTop() to determine the elements on screen position.

`getView()` is called internally by the ListView, when populating the list. You *should not* use it to get the view at that position in the list, as calling `getView()` with null for the `convertView` causes the adapter to inflate a new view from the adapter's layout resource (does not get the view that is already being displayed).
Joe
Excellent point!
+2  A: 

See: http://stackoverflow.com/questions/2001760/android-listview-get-data-index-of-visible-item/2002413#2002413 and combine with part of Feet's answer above, can give you something like:

int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
  Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
  return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);

The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.

Joe