KC Chai
KC Chai

Reputation: 1617

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

Upvotes: 6

Views: 22275

Answers (1)

Mushtaq Jameel
Mushtaq Jameel

Reputation: 7083

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 implemented here.

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.

Upvotes: 13

Related Questions