【发布时间】:2012-11-01 15:44:29
【问题描述】:
我有一个 ListView,其中包含更多元素,然后我可以一次显示。现在我想从所有元素中获取索引,这些元素完全可见(-> 不包括仅部分可见的元素)。
此时我使用getFirstVisiblePosition() & getLastVisiblePosition() 到for-loop 来迭代它们,但是这些方法并不像我想要的那样准确。
有没有更好的解决方案?
【问题讨论】:
我有一个 ListView,其中包含更多元素,然后我可以一次显示。现在我想从所有元素中获取索引,这些元素完全可见(-> 不包括仅部分可见的元素)。
此时我使用getFirstVisiblePosition() & getLastVisiblePosition() 到for-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)。)
【讨论】:
我这样做的方法是扩展您在ListView 适配器的getView 中传递的任何视图,并覆盖方法onAttachedToWindow 和onDetachedToWindow 以跟踪可见的索引。
【讨论】:
试试onScrollListner,你可以使用getFirstVisiblePosition和getLastVisiblePosition。
这个this 链接,它包含类似类型的问题。我想你在那里得到了答案..,.
【讨论】:
上面的代码有些正确。如果您需要找到完全可见的视图位置,请使用以下代码
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.
}
【讨论】: