Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Infinite Scroll Listener - Android
public abstract class InfiniteScrollListener implements AbsListView.OnScrollListener {
private int bufferItemCount = 10;
private int currentPage = 0;
private int itemCount = 0;
private boolean isLoading = true;
public InfiniteScrollListener(int bufferItemCount) {
this.bufferItemCount = 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 < itemCount) {
this.itemCount = totalItemCount;
if (totalItemCount == 0) {
this.isLoading = true; }
}
if (isLoading && (totalItemCount > itemCount)) {
isLoading = false;
itemCount = totalItemCount;
currentPage++;
}
if (!isLoading && (totalItemCount - visibleItemCount)<=(firstVisibleItem + bufferItemCount)) {
loadMore(currentPage + 1, totalItemCount);
isLoading = true;
}
}
}
// Attach the listener to the AdapterView onCreate
yourListView.setOnScrollListener(new InfiniteScrollListener(5) {
@Override
public void loadMore(int page, int totalItemsCount) {
List<HashMap<String, String>> newData = loader.loadData();
dataList.addAll(newData);
adapter.notifyDataSetChanged();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment