我有一个 ListView,其中包含更多元素,然后我可以一次显示。现在我想从所有元素中获取索引,这些元素是完全可见的(-> 不包括仅部分可见的元素)。此时我使用getFirstVisiblePosition()& getLastVisiblePosition()into anfor-loop来迭代它们,但是这些方法并不像我想要的那样准确。
有没有更好的解决方案?
ListView 将其行组织在一个自上而下的列表中,您可以使用getChildAt(). 所以你想要的很简单。让我们获取第一个和最后一个视图,然后检查它们是否完全可见:
// getTop() and getBottom() are relative to the ListView, 
//   so if getTop() is negative, it is not fully visible
int first = 0;
if(listView.getChildAt(first).getTop() < 0)
    first++;
int last = listView.getChildCount() - 1;
if(listView.getChildAt(last).getBottom() > listView.getHeight())
    last--;
// Now loop through your rows
for( ; first <= last; first++) {
    // Do something
    View row = listView.getChildAt(first);
}
添加
现在我想从所有元素中获取索引,这些元素是完全可见的
我不确定那句话是什么意思。如果上面的代码不是您想要的索引,您可以使用:
int first = listView.getFirstVisiblePosition();
if(listView.getChildAt(0).getTop() < 0)
    first++;
拥有一个与您的适配器相关的索引(即adapter.getItem(first).)
我这样做的方法是扩展您传入适配器getView的任何视图ListView并覆盖方法onAttachedToWindow并onDetachedToWindow跟踪可见的索引。
试试 onScrollListner,你可以使用 getFirstVisiblePosition 和 getLastVisiblePosition。
这个这个链接,它包含类似类型的问题。我想你在那里得到了答案......
上面的代码有些正确。如果您需要找到视图的完全可见位置,请使用以下代码
public void onScrollStateChanged(AbsListView view, int scrollState)  {
    // TODO Auto-generated method stub
    View v = null;
    if (scrollState == 0) {
        int first =0;
        if (view.getChildAt(first).getTop() < 0)
            first++;
        int last = list.getChildCount() - 1;
        if (list.getChildAt(last).getBottom() > list
                .getHeight())
            last--;
        // Now loop through your rows
        for ( ; first <= last; first++) {
            // Do something
            View row = view.getChildAt(first);
            // postion for your row............ 
            int i=list.getPositionForView(row);
        }
    }
        // set the margin.
}