首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >安卓:从ListView访问子视图

安卓:从ListView访问子视图
EN

Stack Overflow用户
提问于 2008-11-02 22:40:49
回答 6查看 135.7K关注 0票数 109

我需要找出使用ListView显示的列表中某个元素的像素位置。似乎我应该先获取一个TextView的,然后再使用getTop(),但是我不知道如何获取ListView的子视图。

更新:对于ListViewViewGroup的子项与列表中的项不是一一对应的。相反,ViewGroup的子级只与当前可见的视图相对应,所以getChildAt()ViewGroup内部的索引进行操作,并不一定与ListView使用的列表中的位置有任何关系。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 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的子级,这可能会影响性能。

票数 216
EN

Stack Overflow用户

发布于 2012-01-01 16:20:17

下面的代码更容易使用:

 View rowView = listView.getChildAt(viewIndex);//The item number in the List View
    if(rowView != null)
        {
           // Your code here
        }
票数 18
EN

Stack Overflow用户

发布于 2008-11-02 23:04:55

在文档中快速搜索ListView类,就会发现继承自ViewGroup的getChildCount()和getChildAt()方法。你能用这些遍历它们吗?我不确定,但值得一试。

找到了here

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/257514

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档