我需要找出使用ListView
显示的列表中某个元素的像素位置。似乎我应该先获取一个TextView的,然后再使用getTop()
,但是我不知道如何获取ListView
的子视图。
更新:对于ListView
,ViewGroup
的子项与列表中的项不是一一对应的。相反,ViewGroup
的子级只与当前可见的视图相对应,所以getChildAt()
对ViewGroup
内部的索引进行操作,并不一定与ListView
使用的列表中的位置有任何关系。
发布于 2010-04-21 07:01:58
请看:Android ListView: get data index of visible item和结合上述脚的答案的一部分,可以给你类似的东西:
int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // 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);
这样做的好处是不会遍历ListView的子级,这可能会影响性能。
发布于 2012-01-01 16:20:17
下面的代码更容易使用:
View rowView = listView.getChildAt(viewIndex);//The item number in the List View
if(rowView != null)
{
// Your code here
}
发布于 2008-11-02 23:04:55
在文档中快速搜索ListView类,就会发现继承自ViewGroup的getChildCount()和getChildAt()方法。你能用这些遍历它们吗?我不确定,但值得一试。
找到了here
https://stackoverflow.com/questions/257514
复制相似问题