RecyclerView onScrolled not called when use scrollToPosition

强颜欢笑 提交于 2020-01-13 13:31:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!