7

I have a RecyclerView in my activity and a LinearSnapHelper attached to it:

TimePickerAdapter timePickerAdapter = new TimePickerAdapter(hours);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);

final SnapHelper snapHelper = new LinearSnapHelper();
snapHelper.attachToRecyclerView(recyclerView);

The problem is that when I want to initially scroll to a specific item, the snap helper is not being triggered to attach the item (see the image):

recyclerView.getLayoutManager().scrollToPosition(timePickerAdapter.getCurrentPosition());

When I scroll with my hand it starts to work as expected. Any solutions to this?

enter image description here

dragoon
  • 5,601
  • 5
  • 37
  • 55

3 Answers3

14

SnapHelper rely on RecyclerView.OnFlingListener#onFling() or RecyclerView.OnScrollListener#onScrollStateChanged(recyclerView, RecyclerView.SCROLL_STATE_IDLE) to trigger snap action.

But scrollToPosition() will not tigger above callback. You can invoke smoothScrollBy(1, 0) after scrollToPosition() to trigger SnapHelper to scroll.

Samuel
  • 201
  • 2
  • 5
0

I just encountered the same issue - for me using recyclerView.smoothScrollToPosition(pos) instead of recyclerView.scrollToPosition(pos) did the trick

Katharina
  • 1,612
  • 15
  • 27
  • Thanks for the reply, does it also work for you if the item to which you are scrolling is already visible? For me ``smoothScrollToPosition`` doesn't do anything in that case. – dragoon Jan 11 '17 at 09:03
  • In case of 1000 items it will scroll about 15 seconds. – CoolMind Jan 29 '20 at 09:23
0

If items have the same width and space between them also the same you can use this for initial scroll

recyclerView.apply {
   post {
       val dx = initialPosition * (itemWidth + itemSpace)
       scrollBy(dx, 0)
   }
}
Dmitry Kopytov
  • 341
  • 3
  • 6