Android Endless List

后端 未结 10 1184
梦如初夏
梦如初夏 2020-11-22 02:52

How can I create a list where when you reach the end of the list I am notified so I can load more items?

10条回答
  •  别那么骄傲
    2020-11-22 03:23

    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.

    1. Let your ListFragment or ListActivity implement OnScrollListener
    2. 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.

    3. (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:

      
      
      
      
          
      
          
      
      
      
    4. (optional) Finally, remove that loading indicator by calling listView.removeFooterView(yourFooterView) if there are no more items or pages.

提交回复
热议问题