How can I create a list where when you reach the end of the list I am notified so I can load more items?
Just wanted to contribute a solution that I used for my app.
It is also based on the OnScrollListener
interface, but I found it to have a much better scrolling performance on low-end devices, since none of the visible/total count calculations are carried out during the scroll operations.
ListFragment
or ListActivity
implement OnScrollListener
Add the following methods to that class:
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//leave this empty
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 - threshold) {
currentPage++;
//load more list items:
loadElements(currentPage);
}
}
}
where currentPage
is the page of your datasource that should be added to your list, and threshold
is the number of list items (counted from the end) that should, if visible, trigger the loading process. If you set threshold
to 0
, for instance, the user has to scroll to the very end of the list in order to load more items.
(optional) As you can see, the "load-more check" is only called when the user stops scrolling. To improve usability, you may inflate and add a loading indicator to the end of the list via listView.addFooterView(yourFooterView)
. One example for such a footer view:
(optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView)
if there are no more items or pages.