本文介绍了使用scrollToPosition时未调用RecyclerView onScrolled的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的RecyclerView.OnScrollListener

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);

但是在某些情况下onScrolled不要调用事件RecyclerView已滚动(使用scrollToPositionWithOffset).
我知道原因是当我们使用scrollToPositionWithOffset(或scrollToPosition)onScrolled时,仅当firstVisibleItemlastVisibleItem更改时才调用.您可以在演示中看到(如果未调用firstVisibleItem = 2和lastVisibleItem = 5 => onScrolled,将调用firstVisibleItem = 2和lastVisibleItem = 6 => onScrolled)

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)

使用scrollToPosition时是否有任何技巧可以始终接收onScrolled?

Is there any trick or workaround way for always receive onScrolled when use scrollToPosition?

任何帮助或建议将不胜感激.

Any help or suggestion would be great appreciated.

推荐答案

我发现了
如果RecyclerView滚动(通过使用scrollToPosition),而firstVisibleItemlastVisibleItem不变,则 THEN 不会被调用,而是 View.OnLayoutChangeListener 被调用.

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.

因此,现在我同时使用OnScrollListenerOnLayoutChangeListener收听RecyclerView滚动.

Therefore, now I use both OnScrollListener and OnLayoutChangeListener for listening RecyclerView scroll.

我仍在寻找更好的解决方案

I'm still looking for better solution

这篇关于使用scrollToPosition时未调用RecyclerView onScrolled的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 12:05