Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView onScrolled not called when use scrollToPosition

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?

enter image description here

Any help or suggestion would be great appreciated.

like image 289
Linh Avatar asked Aug 15 '17 04:08

Linh


1 Answers

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

like image 174
Linh Avatar answered Oct 23 '22 07:10

Linh