您可以使用适配器来检测列表视图何时滚动到其底部,正如@darnmason 在上面接受的答案中所做的那样,但我发现有时当列表滚动得非常快时,getView 方法可能无法完成处理适配器中的最后一个位置 last...可能是因为它仍在渲染某个较早的位置。
当我滚动到列表底部时,这个烦人的效果导致一个按钮淡入视野,有时无法呈现。
这里是有烦人效果的解决方案,原则上类似于@darnmason的解决方案:
public abstract class MyAdapter extends BaseAdapter {
public View getView(int position, View convertView, ViewGroup parent) {
//your code for getView here...
if(position == this.getCount() - 1){
onScrollToBottom(position);
}
else{
onScrollAwayFromBottom(position);
}
return convertView;
}
public abstract void onScrollToBottom(int bottomIndex);
public abstract void onScrollAwayFromBottom(int currentIndex);
}
此解决方案检测列表何时滚动到底部以及何时滚动离开底部。
要消除烦人的效果,只需修改如下:
public abstract class MyAdapter extends BaseAdapter {
public View getView(int position, View convertView, ViewGroup parent) {
//your code for getView here...
if(position == this.getCount() - 1){
onScrollToBottom(position);
}
else{
AdapterView adapterView = (AdapterView) parent;
int count = adapterView.getCount();
if(adapterView.getLastVisiblePosition() == count - 1){
//The adapter was faking it, it is already at the bottom!
onScrollToBottom(count - 1);
}
else {
//Honestly! The adapter is truly not at the bottom.
onScrollAwayFromBottom(position);
}
}
return convertView;
}
public abstract void onScrollToBottom(int bottomIndex);
public abstract void onScrollAwayFromBottom(int currentIndex);
}
现在像往常一样调用您的适配器,如下所示:
MyAdapter adapter = new MyAdapter(){
@Override
public void onScrollToBottom(int bottomIndex) {
/*loadMore is a button that fades into view when you are not at the bottom of the list so you can tap and load more data*/
loadMore.show();
}
@Override
public void onScrollAwayFromBottom(int currentIndex) {
/*loadMore is a button that fades out of view when you are not at the bottom of the list*/
loadMore.hide();
}
}
当以这种方式实现时,适配器在检测列表何时滚动到底部时变得非常有效。
它所需要的只是列表中的一点合作!