When you use a List or Grid, sometimes common requirement is to dynamically load more data as the user keeps scrolling down making it a potentially infinite scrolling list. This blog will guide you on how to implement this feature in your app.
We will need is our InfiniteScrollListener class that will implement OnScrollListener. Let’s jump right in and see the code for this class.
public abstract class InfiniteScrollListener implements AbsListView.OnScrollListener { private int mBufferItemCount = 10; private int mCurrentPage = 0; private int mItemCount = 0; private boolean mIsLoading = true; public InfiniteScrollListener(int bufferItemCount) { this.mBufferItemCount = bufferItemCount; } public abstract void loadMore(int page, int totalItemsCount); @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // Do Nothing } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (totalItemCount < mItemCount) { this.mItemCount = totalItemCount; if (totalItemCount == 0) { this.mIsLoading = true; } } if (mIsLoading && (totalItemCount > mItemCount)) { mIsLoading = false; mItemCount = totalItemCount; mCurrentPage++; } if (!mIsLoading && (totalItemCount - visibleItemCount) <= (firstVisibleItem + mBufferItemCount)) { loadMore(mCurrentPage + 1, totalItemCount); mIsLoading = true; } } }
Then in our onCreate of Activity We must put this:
mGridView.setOnScrollListener(new InfiniteScrollListener(5) { @Override public void loadMore(int page, int totalItemsCount) { mProgressDialog.show(); // your code } });