问题
I have RecyclerView.OnScrollListener
like this
findViewById(R.id.button_scroll_to_position).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mLinearLayoutManager.scrollToPositionWithOffset(2,0);
}
});
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.i("TAG", "scroll " + dy);
}
});
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 7; i++) {
list.add("" + i);
}
mRecyclerView.setAdapter(new SimpleRVAdapter(list));
mLinearLayoutManager.scrollToPositionWithOffset(2,0);
However in some case onScrolled
don't call event RecyclerView
have scrolled (using scrollToPositionWithOffset
).
I know the reason is when we use scrollToPositionWithOffset
(or scrollToPosition
) onScrolled
only call when firstVisibleItem
and lastVisibleItem
change. You can see in the demo (if firstVisibleItem=2 and lastVisibleItem=5 => onScrolled not called, firstVisibleItem=2 and lastVisibleItem=6 => onScrolled will called)
Is there any trick or workaround way for always receive onScrolled
when use scrollToPosition
?
Any help or suggestion would be great appreciated.
回答1:
I found that
if RecyclerView
is scrolled (by using scrollToPosition) while firstVisibleItem
and lastVisibleItem
does not change THEN RecyclerView.OnScrollListener
is not called but View.OnLayoutChangeListener is called.
Therefore, now I use both OnScrollListener
and OnLayoutChangeListener
for listening RecyclerView
scroll.
I'm still looking for better solution
回答2:
I know I'm necroing thread but just in case someone runs into it like I did...
If you don't care about animation use:
recyclerView.smoothScrollToPosition(position);
It will trigger
OnScrollListener.onScrolled(RecyclerView recyclerView, int dx, int dy)
回答3:
While you call scrollToPosition()
onScroll never called.
From the documentation
Convenience method to scroll to a certain position. RecyclerView does not implement scrolling logic, rather forwards the call to scrollToPosition(int)
So scrollToPosition(int)
is not implementing the scrolling logic.
For more info look at this link.https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html#scrollToPosition(int)
来源:https://stackoverflow.com/questions/45686356/recyclerview-onscrolled-not-called-when-use-scrolltoposition