6

我的 setOnScrollListener 有问题。每当我滚动到列表视图的底部时,它就会一直调用我的异步任务。如何将 setOnScrollListener 设置为仅在到达底部时才加载。

listview.setAdapter(adapter);
mProgressDialog.dismiss();

listview.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) { 
        // TODO Auto-generated method stub
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        int lastInScreen = firstVisibleItem + visibleItemCount;
        if (lastInScreen == totalItemCount) {
            new loadmore().execute();
        } else {
        }
    }
);
4

1 回答 1

13

每当您向下滚动列表视图时,都会调用 OnScroll 方法,因此最好的选择是使用某种填充,就像这里实现的那样。

public class EndlessScrollListener implements OnScrollListener 

    private int visibleThreshold = 5;
    private int currentPage = 0;
    private int previousTotal = 0;
    private boolean loading = true;

    public EndlessScrollListener() {
    }
    public EndlessScrollListener(int visibleThreshold) {
        this.visibleThreshold = visibleThreshold;
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        if (loading) {
            if (totalItemCount > previousTotal) {
                loading = false;
                previousTotal = totalItemCount;
                currentPage++;
            }
        }
        if (!loading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
            // I load the next page of gigs using a background task,
            // but you can call any function here.
            new LoadGigsTask().execute(currentPage + 1);
            loading = true;
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }
}

visibleThreshold – 在加载更多之前,当前滚动位置下方的最小项目数量。

currentPage – 您已加载的当前数据页

previousTotal – 上次加载后数据集中的项目总数

loading – 如果我们仍在等待最后一组数据加载,则为真。

于 2013-07-04T15:48:59.777 回答