Reputation: 5743
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?
Upvotes: 7
Views: 4881
Reputation: 361
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)
}
}
Upvotes: 0
Reputation: 231
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.
Upvotes: 14
Reputation: 1642
I just encountered the same issue - for me using recyclerView.smoothScrollToPosition(pos)
instead of recyclerView.scrollToPosition(pos)
did the trick
Upvotes: 0