How to implement Infinite Scrolling with RecyclerView?

前端 未结 5 1854
一生所求
一生所求 2020-12-20 00:03

I have a recycler and inside of it there are cardviews where I fetch information from a REST service, I\'m trying to implement an endless scroll, It\'s supposed that user wi

5条回答
  •  独厮守ぢ
    2020-12-20 00:27

    When writing RecyclerView.Adapter, you anyway need to provide the getItemCount method that returns the correct number of items (may be large). RecyclerView will call on its own initiative the onBindViewHolder(holder, position) method of this adapter. All you need is to provide functionality of retrieving data, relevant to this position. There is no difference at all, if your list is smaller than screen, slightly larger than screen or Integer.MAX_VALUE size. RecyclerView will take care not to fetch/allocate too much extra items.

    You do not need to implement scroll listeners or otherwise explicitly handle the scrolling.

    The only tricky part is that you may need to take a long action like server call to get some items. Then just return uninitialized holder (empty view) on the first invocation and start fetching the needed row in the background thread. When you have it, call notifyDataSetChanged or notifyItemRangeChanged, and RecyclerView will take care to update itself.

    For performance reasons I would strongly recommend to update content in chunks of the fixed size rather than sending individual server request per every row displayed. For some public servers like Google Books this is clearly a requirement, as they have quota limits per request.

    If you need to view the full source code on how this possibly could be implemented, there is an open source project here in GitHub.

提交回复
热议问题