Reputation: 153
I am using RecyclerView to show list of items. The total items are 10, but visible at a time is 3. But when i use recyclerView.getChildCount() method to get the visible count, it is giving me 10, instead of 3. What can be the issue. I am trying to implement pagination. So everytime my visible count is coming same as totalitemcount, and as a result my load more is getting called continuously till all the pages are loaded. Below is my code.
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
onScrolled();
}
visibleItemCount = recyclerView.getChildCount();
totalItemCount = mLinearLayoutManager.getItemCount();
firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if (totalItemCount > previousTotal) {
loading = false;
previousTotal = totalItemCount;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// End has been reached
// Do something
current_page++;
onLoadMoreData(current_page);
loading = true;
}
}
Upvotes: 4
Views: 6818
Reputation: 296
To get the number of items visible on the screen of the recycler view.
rvBreakingNews.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val mLayoutManger = recyclerView.layoutManager as LinearLayoutManager
//To get the total Number of items visible on the screen
val visibleItemCount = mLayoutManger.childCount
//To get the total items loaded in the RecyclerView
val totalItemCount = mLayoutManger.itemCount
})
Upvotes: 0
Reputation: 4376
Check this answer: Get visible items in RecyclerView
LinearLayoutManager layoutManager = ((LinearLayoutManager)mRecyclerView.getLayoutManager());
int visibleItemCount = layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition();
Hope it helps.
Upvotes: 7