I need to make my RecyclerView
load only 10 items and load more 10 after scrolling and work like this.
I was add the items in array using Volley
Try using this scroll listener with your recyclerview
.
In load more items place your logic to load more items.
isLastPage
will return true if there are no items to load.
isLoading
will be true while you are fetching data and false when you have fetched the data.
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
/**
* Pagination class to add more items to the list when reach the last item.
*/
abstract class PaginationScrollListener
/**
* Supporting only LinearLayoutManager for now.
*
* @param layoutManager
*/
(var layoutManager: LinearLayoutManager) : RecyclerView.OnScrollListener() {
abstract fun isLastPage(): Boolean
abstract fun isLoading(): Boolean
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val visibleItemCount = layoutManager.childCount
val totalItemCount = layoutManager.itemCount
val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
if (!isLoading() && !isLastPage()) {
if (visibleItemCount + firstVisibleItemPosition >= totalItemCount && firstVisibleItemPosition >= 0) {
loadMoreItems()
}// && totalItemCount >= ClothesFragment.itemsCount
}
}
abstract fun loadMoreItems()
}
Add this to your recyclerview
var isLastPage: Boolean = false
var isLoading: Boolean = false
recyclerView?.addOnScrollListener(object : PaginationScrollListener(your_layoutManager) {
override fun isLastPage(): Boolean {
return isLastPage
}
override fun isLoading(): Boolean {
return isLoading
}
override fun loadMoreItems() {
isLoading = true
//you have to call loadmore items to get more data
getMoreItems()
}
})
fun getMoreItems() {
//after fetching your data assuming you have fetched list in your
// recyclerview adapter assuming your recyclerview adapter is
//rvAdapter
after getting your data you have to assign false to isLoading
isLoading = false
rvAdapter.addData(list)
}
Now in your recyclerview
adapter add the following method.
Here the list is the list which feeds your recyclerview
in your Adapter.
Make sure you initialize the list in your recyclerview
.
fun addData(listItems: ArrayList<yourObject>) {
var size = this.listItems.size
this.listItems.addAll(listItems)
var sizeNew = this.listItems.size
notifyItemRangeChanged(size, sizeNew)
}