简体   繁体   中英

Android ListView setOnScrollListener

I'm having problem with my setOnScrollListener. It just keeps calling my asynctask whenever I scroll to the bottom of the listview. How do I set the setOnScrollListener to load only once I reach the bottom.

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 {
        }
    }
);

OnScroll method is called whenever you scroll down the list view, so the best bet for you to is to use some kind of padding, like the one implementedhere .

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 – The minimum amount of items to have below your current scroll position, before loading more.

currentPage – The current page of data you have loaded

previousTotal – The total number of items in the dataset after the last load

loading – True if we are still waiting for the last set of data to load.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM