David David - 5 months ago 87
Android Question

RecyclerView scrollToPosition not trigger scrollListener

I'm using RecyclerView, with ScrollListener:

mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener()
{
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState)
{
super.onScrollStateChanged(recyclerView, newState);
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
super.onScrolled(recyclerView, dx, dy);
// Do my logic
}
});


When I scroll with the finger, the scroll listener triggered fine.

But when I scroll progrematically, like that:

mRecyclerView.scrollToPosition(LAST_POSITION);


The scroll listener is not triggered.

Answer

This is a known issue. It is caused by the fact that RecyclerView does not know how LayoutManager will handle the scroll or if it will handle it at all.

In the next release, you'll receive a call to onScrolled if first and or last child position changes after a layout (which is generally the result of calling scroll to position).

Unfortunately, dx and dy will be 0 because RecyclerView does not really know how much layout manager did scroll to handle scrollTo request. Alternatively, you can also use the the ViewTreeObserver's scroll callback.