Reputation: 2015
I've got a recyclerView
within a pull to refresh layout
.
I've added an onScrollListener
to keep track of the total vertical movement by adding/subtracting the delta Y (dy)
to a variable named totalScrolled
.
And if the recyclerview
is scrolled fully to the top totalScrolled
should be 0 and a view should be visible.
Problem only is that somehow there is a bug and the scroll listener
is not accurate in telling me how much the list has scrolled
. After scrolling down and back up again through my many items list somehow the totalScrolled
doesn't return to 0.
Anyone ran into this issue as well and knows how to solve this?
Upvotes: 1
Views: 6007
Reputation: 2015
Instead of using the dy from the scrollListener's onScrolled callback to keep track of the total vertical scroll which is inaccurate I use a function from the recyclerView itself - RecyclerView.computeVerticalScrollOffset() - which accurately keeps track of how many pixels the recyclerView has scrolled.
My code looks something like this:
home_screen_recycler.addOnScrollListener(object: RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val scrollOffset = home_screen_recycler.computeVerticalScrollOffset()
presenter.onListScrolled(scrollOffset)
}
})
Upvotes: 4
Reputation: 741
In my project I use this logic.
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (arrayList.size() == 0)
return;
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
int itemPosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
if (itemPosition == (arrayList.size() - 1)) {
// here you can fetch new data from server.
}
}
}
});
Upvotes: 0